Therefore you need to implement IInstanceProvider:
public class MyServiceInstanceProvider : IInstanceProvider
{
public object GetInstance(System.ServiceModel.InstanceContext instanceContext, System.ServiceModel.Channels.Message message)
{
object instance = null;
instance = new MyService();
return instance;
}
public object GetInstance(System.ServiceModel.InstanceContext instanceContext)
{
return GetInstance(instanceContext, null);
}
public void ReleaseInstance(System.ServiceModel.InstanceContext instanceContext, object instance)
{
IDisposable disposableInstance = instance as IDisposable;
if (disposableInstance != null) disposableInstance.Dispose();
}
}
and IServiceBehavior (where the custom provider is attached to the endpoints)
public class MyServiceServiceBehavior : IServiceBehavior
{
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
{
ChannelDispatcher cd = cdb as ChannelDispatcher;
if (cd != null)
{
foreach (EndpointDispatcher ed in cd.Endpoints)
{
ed.DispatchRuntime.InstanceProvider = new MyServiceInstanceProvider();
}
}
}
}
public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) { }
public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase) { }
}
The service behavior is added in code here
ServiceHost serviceHost = new ServiceHost(typeof(MyService));
serviceHost.Description.Behaviors.Add(new MyServiceServiceBehavior());
serviceHost.Open();
No comments:
Post a Comment