具有多个依赖实现的WCF服务

时间:2010-11-01 12:33:27

标签: wcf dependency-injection unity-container

我有一个将从各个客户端调用的WCF服务。

WCF服务在内部使用ISomething。这个接口有多个实现,我需要一些客户端使用一个实现,其他客户端使用不同的实现。

此外,我正在使用Unity和IoC容器。我通常会设置一个自定义工厂来允许wcf服务本身及其依赖图解析,但如果我有一个依赖项的多个实现,我认为我不能采用这种方法,并且不得不求助于解决服务中的ISomething(有效地使用Unity作为服务定位器)并不理想。

所以我需要解决

(1)如何指定客户端需要哪种ISomething实现(例如,使用头,在每个方法中传递实现字符串,托管多个端点等)。

(2)Unity如何适应?

1 个答案:

答案 0 :(得分:2)

一个选项是编写一个为您执行选择的装饰器:

public class RoutingSomething : ISomething
{
    private readonly ISomeContext ctx;
    private readonly ISomething s1;
    private readonly ISomething s2;
    private readonly ISomething s3;

    public RoutingSomething(ISomeContext ctx)
    {
        this.ctx = ctx;

        // An even better design would be to inject these too
        this.s1 = new BarSomething();
        this.s2 = new BazSomething();
        this.s3 = new QuxSomething();
    }

    // Assuming ISomething has a Foo method:
    public void Foo()
    {
        if(this.ctx.Bar())
        {
            this.s1.Foo();
            return;
        }
        if(this.ctx.Baz())
        {
            this.s2.Foo();
            return;
        }
        if(this.ctx.Qux())
        {
            this.s3.Foo();
            return;
        }
    }
}

您可以对此进行概括,以便ISomeContext只是ISomething的抽象工厂。然后开始变成general solution to varying dependencies based on run-time context

您现在可以在Unity中注册RoutingSomething以及其他组件。当容器解析服务时,它会向其中注入一个RoutingSomething实例。

相关问题