简体   繁体   English

简单的注射器条件注射

[英]Simple Injector conditional injection

Lets say I have two Controllers: ControllerA and ControllerB. 假设我有两个控制器:ControllerA和ControllerB。 Both of those controllers accept as parameter IFooInterface. 这两个控制器都接受参数IFooInterface。 Now I have 2 implementation of IFooInterface, FooA and FooB. 现在我有2个IFooInterface,FooA和FooB的实现。 I want to inject FooA in ControllerA and FooB in ControllerB. 我想在ControllerA中注入FooA,在ControllerB中注入FooB。 This was easily achieved in Ninject, but I'm moving to Simple Injector due to better performance. 这很容易在Ninject中实现,但由于性能更好,我正在转向Simple Injector。 So how can I do this in Simple Injector? 那么我怎样才能在Simple Injector中做到这一点? Please note that ControllerA and ControllerB resides in different assemblies and are loaded dynamically. 请注意,ControllerA和ControllerB驻留在不同的程序集中并动态加载。

Thanks 谢谢

Since version 3 Simple Injector has RegisterConditional method 由于版本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);

The SimpleInjector documentation calls this context-based injection . SimpleInjector文档调用此基于上下文的注入 As of version 3, you would use RegisterConditional . 从版本3开始,您将使用RegisterConditional As of version 2.8, this feature isn't implemented in SimpleInjector, however the documentation contains a working code sample implementing this feature as extensions to the Container class. 从版本2.8开始,此功能未在SimpleInjector中实现,但是文档包含实现此功能的工作代码示例,作为Container类的扩展。

Using those extensions methods you would do something like this: 使用这些扩展方法,您可以执行以下操作:

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