以防万一您需要类似的东西,我有一个可行的解决方案,我已在此处发布
public class MefDataServiceHostFactory : DataServiceHostFactory
{
protected override ServiceHost CreateServiceHost(
Type serviceType, Uri[] baseAddresses)
{
ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);
host.Description.Behaviors.Add(new MefServiceBehavior());
return host;
}
}
public class MefInstanceProvider : IInstanceProvider
{
#region fields
private readonly Type _serviceType;
private IDependencyScope _diScope;
#endregion
#region ctor
public MefInstanceProvider(Type serviceType)
{
_serviceType = serviceType;
}
#endregion
public object GetInstance(InstanceContext instanceContext)
{
return GetInstance(instanceContext, null);
}
这是可以使用 MEF 或任何 IOC 的重要部分。
public object GetInstance(InstanceContext instanceContext, Message message)
{
_diScope = GlobalConfiguration.Configuration.DependencyResolver.BeginScope();
return _diScope.GetService(_serviceType);
}
public void ReleaseInstance(InstanceContext instanceContext, object instance)
{
if (_diScope != null) _diScope.Dispose();
}
}
获取一个新实例并处理请求
public class MefServiceBehavior : IServiceBehavior
{
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
{
var cd = cdb as ChannelDispatcher;
if (cd != null)
{
foreach (EndpointDispatcher ed in cd.Endpoints)
{
ed.DispatchRuntime.InstanceProvider = new MefInstanceProvider(serviceDescription.ServiceType);
}
}
}
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,
Collection<ServiceEndpoint> endpoints,
BindingParameterCollection bindingParameters)
{
}
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
}
在 svc 文件中注册自定义工厂
<%@ServiceHost Service="DataService"
Factory="MefDataServiceHostFactory"
language=c# Debug="true" %>
或添加新的服务路线。
routes.Add(new ServiceRoute(string.Empty, new MefDataServiceHostFactory(), typeof (DataService)));
快乐编码!