Conditional injection of a simple injector

Let's say I have two controllers: ControllerA and ControllerB. Both of these controllers accept IFooInterface as a parameter. Now I have 2 implementations of IFooInterface, FooA and FooB. I want to introduce FooA in ControllerA and FooB in ControllerB. This was easily achieved at Ninject, but I am switching to Simple Injector due to better performance. So how can I do this in Simple Injector? Note that ControllerA and ControllerB are in different assemblies and load dynamically.

thanks

+7
c # dependency-injection simple-injector
source share
2 answers

The SimpleInjector documentation invokes this contextual injection . Starting with version 3, you should use RegisterConditional . Starting with version 2.8, this function is not implemented in SimpleInjector, however, the documentation contains an example of working code that implements this function as extensions to the Container class.

Using these extension methods, you will 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; } }); 
+5
source share

Since version 3 of Simple Injector has a 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); 
+12
source share

All Articles