Simple Injector 条件注入

Simple Injector conditional injection

假设我有两个控制器:ControllerA 和 ControllerB。这两个控制器都接受 IFooInterface 作为参数。现在我有 2 个 IFooInterface、FooA 和 FooB 的实现。我想在 ControllerA 中注入 FooA,在 ControllerB 中注入 FooB。这在 Ninject 中很容易实现,但由于性能更好,我正在转向 Simple Injector。那么如何在 Simple Injector 中执行此操作?请注意,ControllerA 和 ControllerB 位于不同的程序集中,并且是动态加载的。

谢谢

SimpleInjector 文档将此 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 称为 Container class 的扩展。

使用这些扩展方法,您可以执行如下操作:

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

因为版本 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);