繁体   English   中英

IoC / DI:当存在同一接口的多个实现时,如何注入特定实例

[英]IoC/DI: How to inject specific instance when there are multiple implementations of same interface

假设我们有两个IService接口的实现:

public interface IService { }

public class Service1 : IService { }

public class Service2 : IService { }

然后,我们有两个依赖于IService

public class Consumer1
{
    public Consumer1(IService svc) { }
}

public class Consumer2
{
    public Consumer2(IService svc) { }
}

现在,如何使用Simple Injector作为依赖关系容器而不使用工厂或单独的接口将Service1注入Consumer1Service2注入Consumer2

如何存档的通用模式(与特定的DI容器无关)也很好:)

UPDATE
我已经尝试过使用简单注入器进行基于上下文的注入。 该文档非常有限,最终得到以下代码:

container.RegisterConditional(
    typeof(IService),
    typeof(Service1),
    Lifestyle.Transient,
    c => c.Consumer.ImplementationType == typeof(Consumer1));

container.RegisterConditional(
    typeof(IService),
    typeof(Service2),
    Lifestyle.Transient,
    c => c.Consumer.ImplementationType == typeof(Consumer2));

container.Register<Consumer1>();
container.Register<Consumer2>();

但是我得到一个例外

配置无效。 创建类型为Consumer1的实例失败。 Consumer1类型的构造函数包含名称为'svc'的参数和未注册的IService类型。 请确保已注册IService,或更改Consumer1的构造函数。 存在1个适用于IService的IService条件注册,但是在提供Consumer1的上下文信息时,其提供的谓词未返回true。

我尝试了不同的谓词变体,但没有成功...

c => c.Consumer.Target.TargetType == typeof(Consumer1)
c => c.Consumer.ServiceType == typeof(Consumer1)

我无法使用最新版本的SI(3.1)重现此问题。 该测试通过:

[Test]
public void Test1()
{
    var container = new Container();

    container.RegisterConditional<IService, Service1>(
        c => c.Consumer.ImplementationType == typeof(Consumer1));
    container.RegisterConditional<IService, Service2>(
        c => c.Consumer.ImplementationType == typeof(Consumer2));
    container.Register<Consumer1>();
    container.Register<Consumer2>();

    container.Verify();

    var result1 = container.GetInstance<Consumer1>();
    var result2 = container.GetInstance<Consumer2>();

    Assert.IsInstanceOf<Service1>(result1.Svc);
    Assert.IsInstanceOf<Service2>(result2.Svc);
}

您使用的是哪个版本的SI,您确定使用的是正确的container实例吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM