簡體   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