WCF和Unity - 依赖注入

时间:2010-03-23 11:07:16

标签: wcf dependency-injection unity-container

我正试图通过依赖注入来阻止WCF。我发现的所有示例都基于您使用.svc(ServiceHostFactory)服务或使用app.config配置容器的假设。其他示例也基于容器被传递给类。

我想要一个解决方案,其中容器不会被传递(不与Unity紧密耦合)。我没有使用配置文件来配置容器以及我在哪里使用自托管服务。

问题是 - 正如我所看到的 - ServiceHost将服务实现的类型作为参数,因此使用InstanceProvider会有什么不同?

我目前提出的解决方案是将ServiceHost(或专业化)注册为具有名称的类型(例如container.RegisterInstance<Type>("ServiceName", typeof(Service);)。

然后container.RegisterType<UnityServiceHost>(new InjectionConstructor(new ResolvedParameter<Type>("ServiceName")));注册ServiceHost。

那里有更好的解决方案吗?我可能是我的假设。

最好的问候,
迈克尔

1 个答案:

答案 0 :(得分:3)

使用构造函数注入连接您的服务实现,就像使用任何其他类一样。

Here's a writeup on how to make WCF understand Constructor Injection

该答案中的示例演示了穷人注射,但您可以从中推断并在ServiceHostFactory中设置UnityContainer实例,而不是硬编码依赖项。

您将容器实例一直传递给自定义IInstanceProvider。现在,您可以在GetInstance方法中使用容器:

public object GetInstance(InstanceContext instanceContext)
{
    var serviceType = instanceContext.Host.Description.ServiceType;
    return this.container.Resolve(serviceType);
}
相关问题