简单的注射器条件注射

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

谢谢

SimpleInjector文档调用此基于上下文的注入 。 从版本3开始,您将使用RegisterConditional 。 从版本2.8开始,此function未在SimpleInjector中实现,但是文档包含实现此function的工作代码示例,作为Container类的扩展。

使用这些扩展方法,你会做这样的事情:

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

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

 container.RegisterConditional(c => c.Consumer.ImplementationType == typeof(ControllerA)); container.RegisterConditional(c => c.Consumer.ImplementationType == typeof(ControllerB)); container.RegisterConditional(c => !c.Handled);