2010-03-23 159 views
4

我试图用依赖注入来锁定WCF。我发现的所有示例都基于假设您使用.svc(ServiceHostFactory)服务或使用app.config来配置容器。其他的例子也是基于容器被传递给类。WCF和Unity - 依赖注入

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

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

溶液我已经想出了此刻是注册的ServiceHost(或专门化)的注册的名称(例如container.RegisterInstance<Type>("ServiceName", typeof(Service);)一个类型。

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

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

最好的问候,
迈克尔

回答

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); 
} 
+0

是的,我不喜欢绕过容器。我会尝试使用泛型。 – Michael 2010-03-23 15:16:14

+0

什么时候在InstanceProvider上调用GetInstance?当我打开服务主机? – Michael 2010-03-23 15:17:29

+0

您只能在这三个WCF类(ServiceHostFactory,ServiceHost和IInstanceProvider)中传递容器。这几乎不是Service Locator的反模式 - 它只是DI基础设施。你甚至可以创建一个围绕Unity的通用库。温莎城堡的WcfFacility就是这么做的。要回答您的其他问题:每次调用服务操作时都会调用GetInstance。 – 2010-03-23 15:23:18