Search code examples
c#.netdependency-injectionsimple-injector

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


Solution

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