依赖注入WCF [英] Dependency Injection wcf

查看:168
本文介绍了依赖注入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.

推荐答案

当您使用的 svcutil.exe的的或的添加服务引用的向导在Visual Studio中,人们的许多类型的自动生成将一个客户端接口。让我们把它叫做 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< T> 作为实现:

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配置DI容器MyServiceFactory。下面是它是如何在温莎城堡进行:

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>());

奖励信息:这里的<一个href="http://stackoverflow.com/questions/2042609/injecting-data-to-a-wcf-service/2042858#2042858">how要连接一个WCF服务与DI容器。

这篇关于依赖注入WCF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆