简单的注射器条件注射

Dav*_*ita 7 .net c# dependency-injection simple-injector

假设我有两个控制器:ControllerA和ControllerB.这两个控制器都接受参数IFooInterface.现在我有2个IFooInterface,FooA和FooB的实现.我想在ControllerA中注入FooA,在ControllerB中注入FooB.这很容易在Ninject中实现,但由于性能更好,我正在转向Simple Injector.那么我怎样才能在Simple Injector中做到这一点?请注意,ControllerA和ControllerB驻留在不同的程序集中并动态加载.

谢谢

Mik*_*nov 15

由于版本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);
Run Code Online (Sandbox Code Playgroud)


Mik*_*ray 5

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;
    }
});
Run Code Online (Sandbox Code Playgroud)