依赖注入 wcf [英] Dependency Injection wcf
问题描述
我想在 WCF 中注入我的接口的实现,但我想在 WCF 的客户端中初始化我的依赖注入容器.所以我可以为我的服务的每个客户端使用不同的实现.
I want inject a implementation of my Interface in the WCF but I want initialize my container of Dependency Injection in the Client of the WCF. So I can have a different implementation for each client of the my service.
推荐答案
当您在 Visual Studio 中使用 svcutil.exe 或 添加服务引用 向导时,许多自动生成的类型将是客户端界面.我们称之为IMyService
.还将有另一个自动生成的接口,称为IMyServiceChannel
之类的东西,它实现了 IMyService 和 IDisposable.在客户端应用程序的其余部分中使用此抽象.
When you use svcutil.exe or the Add Service Reference wizard in Visual Studio, one of the many types auto-generated will be a client interface. Let's call it IMyService
. There will also be another auto-generated interface called something like IMyServiceChannel
that implements IMyService and IDisposable. Use this abstraction in the rest of your client application.
既然你希望能够创建一个新的频道并再次关闭它,你可以引入一个抽象工厂:
Since you want to be able to create a new channel and close it again, you can introduce an Abstract Factory:
public interface IMyServiceFactory
{
IMyServiceChannel CreateChannel();
}
在客户端应用程序的其余部分,您可以依赖 IMyServiceFactory:
In the rest of your client application, you can take a dependency on IMyServiceFactory:
public class MyClient
{
private readonly IMyServiceFactory factory;
public MyClient(IMyServiceFactory factory)
{
if (factory == null)
{
throw new ArgumentNullException("factory");
}
this.factory = factory;
}
// Use the WCF proxy
public string Foo(string bar)
{
using(var proxy = this.factory.CreateChannel())
{
return proxy.Foo(bar);
}
}
}
您可以创建一个 IMyServiceFactory 的具体实现,它将 WCF 的 ChannelFactory
包装为一个实现:
You can create a concrete implementation of IMyServiceFactory that wraps WCF's ChannelFactory<T>
as an implementation:
public MyServiceFactory : IMyServiceFactory
{
public IMServiceChannel CreateChannel()
{
return new ChannelFactory<IMyServiceChannel>().CreateChannel();
}
}
您现在可以通过将 IMyServiceFactory 映射到 MyServiceFactory 来配置您的 DI 容器.以下是在温莎城堡中的做法:
You can now configure your DI Container by mapping IMyServiceFactory to MyServiceFactory. Here's how it's done in Castle Windsor:
container.Register(Component
.For<IMyServiceFactory>()
.ImplementedBy<MyServiceFactory>());
奖励信息:这是如何将 WCF 服务与DI 容器.
这篇关于依赖注入 wcf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!