簡體   English   中英

簡單的注射器條件注射

[英]Simple Injector conditional injection

假設我有兩個控制器:ControllerA和ControllerB。 這兩個控制器都接受參數IFooInterface。 現在我有2個IFooInterface,FooA和FooB的實現。 我想在ControllerA中注入FooA,在ControllerB中注入FooB。 這很容易在Ninject中實現,但由於性能更好,我正在轉向Simple Injector。 那么我怎樣才能在Simple Injector中做到這一點? 請注意,ControllerA和ControllerB駐留在不同的程序集中並動態加載。

謝謝

由於版本3 Simple Injector具有RegisterConditional方法

container.RegisterConditional<IFooInterface, FooA>(c => c.Consumer.ImplementationType == typeof(ControllerA));
container.RegisterConditional<IFooInterface, FooB>(c => c.Consumer.ImplementationType == typeof(ControllerB));
container.RegisterConditional<IFooInterface, DefaultFoo>(c => !c.Handled);

SimpleInjector文檔調用此基於上下文的注入 從版本3開始,您將使用RegisterConditional 從版本2.8開始,此功能未在SimpleInjector中實現,但是文檔包含實現此功能的工作代碼示例,作為Container類的擴展。

使用這些擴展方法,您可以執行以下操作:

Type fooAType = Assembly.LoadFrom(@"path\to\fooA.dll").GetType("FooA");
Type fooBType = Assembly.LoadFrom(@"path\to\fooB.dll").GetType("FooB");
container.RegisterWithContext<IFooInterface>(context => {
    if (context.ImplementationType.Name == "ControllerA") 
    {
        return container.GetInstance(fooAType);
    } 
    else if (context.ImplementationType.Name == "ControllerB") 
    {
        return container.GetInstance(fooBType)
    } 
    else 
    {
        return null;
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM