Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Injector conditional injection

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

like image 883
Davita Avatar asked Jan 03 '15 00:01

Davita


2 Answers

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);
like image 112
Michael Chudinov Avatar answered Oct 23 '22 08:10

Michael Chudinov


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;
    }
});
like image 5
Mike Zboray Avatar answered Oct 23 '22 09:10

Mike Zboray