您需要通過實現IServiceBehavior編寫servicebehavior,並使用實例提供程序初始化服務實例。下面初始化一個新的服務實例,您可以實現不同的邏輯:
public class XInstanceProviderServiceBehavior : Attribute, IServiceBehavior
{
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (var item in serviceHostBase.ChannelDispatchers)
{
var dispatcher = item as ChannelDispatcher;
if (dispatcher != null)
{
dispatcher.Endpoints.ToList().ForEach(endpoint =>
{
endpoint.DispatchRuntime.InstanceProvider = new XInstanceProvider(serviceDescription.ServiceType);
});
}
}
}
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
}
,讓您的實例提供的類實現IInstanceProvider和getInstance方法返回相關的實例。
public XInstanceProvider :IInstanceProvider
{
...
public object GetInstance(InstanceContext instanceContext, System.ServiceModel.Channels.Message message)
{
return new ServiceX();
}
}
然後,您只需要添加servicebehaviour服務;像
[XInstanceProviderServiceBehavior()]
public class MyService : IMyService