Simple Injector conditional injection

不打扰是莪最后的温柔 提交于 2020-01-02 02:51:28

问题


Lets say I have two Controllers: ControllerA and ControllerB. Both of those controllers accept as parameter IFooInterface. Now I have 2 implementation of IFooInterface, FooA and FooB. I want to inject FooA in ControllerA and FooB in ControllerB. This was easily achieved in Ninject, but I'm moving to Simple Injector due to better performance. So how can I do this in Simple Injector? Please note that ControllerA and ControllerB resides in different assemblies and are loaded dynamically.

Thanks


回答1:


The SimpleInjector documentation calls this context-based injection. As of version 3, you would use 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.

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;
    }
});



回答2:


Since version 3 Simple Injector has RegisterConditional method

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);


来源:https://stackoverflow.com/questions/27750322/simple-injector-conditional-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!