问题
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