这对我有用:
创建一个具体的上下文接口:
public class CustomersContext :DbContext, ICustomerContext
然后在容器中注册为单例
container.Register(Component.For<ICustomerContext>().ImplementedBy<CustomersContext>());
那么你应该将它注册为 WCF 服务并提供你自己的 Instance Provider
像这样:
首先给你的界面添加一些属性:
[InstanceProviderBehavior(typeof (ICustomerContext))]
[DataContract]
public class CustomersContext :DbContext, ICustomerContext
然后,编写InstanceProviderBehavior属性:
public class InstanceProviderBehaviorAttribute : Attribute, IServiceBehavior
{
private readonly Type _type;
public InstanceProviderBehaviorAttribute(Type type)
{
_type = type;
}
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher cd in serviceHostBase.ChannelDispatchers)
{
foreach (EndpointDispatcher ed in cd.Endpoints)
{
if (!ed.IsSystemEndpoint)
{
ed.DispatchRuntime.InstanceProvider = new WindsorServiceInstanceProvider(_type);
}
}
}
}
}
请注意,您告诉 WCF 使用 WindsorServiceInstanceProvider。
这里是:
public class WindsorServiceInstanceProvider : IInstanceProvider
{
public static IWindsorContainer Container;
private readonly Type _type;
public WindsorServiceInstanceProvider(Type type)
{
_type = type;
}
public object GetInstance(InstanceContext instanceContext, Message message)
{
return Container.Resolve(_type);
}
public object GetInstance(InstanceContext instanceContext)
{
return this.GetInstance(instanceContext, null);
}
public void ReleaseInstance(InstanceContext instanceContext, object instance)
{
Container.Release(instance);
}
}
请注意名为 Container 的静态对象,这很丑陋,但我没有找到任何其他方法将我的容器实例传递给 InstanceProvider
就是这样。现在,当某些客户端从您的 WCF 服务中请求 ICustomerContext 时,它会从您的容器中解析它。
更多关于 WCF 实例提供者here