【问题标题】:Singleton DBContext for a Per-Call WCF Service using castle使用城堡的 Per-Call WCF 服务的单例 DBContext
【发布时间】:2014-02-24 15:53:44
【问题描述】:

我正在尝试找到一种将 EF6 DbContext 注入我的 WCF 服务的正确方法,但我很难找到一个合适的工作示例。有谁知道每次调用 WCF 服务和实体框架的良好演示?我使用 Castle 进行注射,但欢迎任何其他 IOC 容器。如果您反对使用 Singleton dbcontext [Massive DB],请向我展示一个性能影响最小的工作示例。

【问题讨论】:

  • 请参阅this answer,了解为什么单身DbContext 是个坏主意。

标签: wcf entity-framework singleton castle-windsor dbcontext


【解决方案1】:

这对我有用: 创建一个具体的上下文接口:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多