Search code examples
c#dependency-injectionsimple-injector

Injecting different dependencies with Simple Injector depending on assembly


I have two different IContext implementations living in different assemblies (in fact they are in different solutions). These assemblies are both used in a single parent project. This parent project uses SimpleInjector for DI.

Is there a way of getting Simple Injector to inject/register different implementations based on the assembly location of the class being injected into?.

In pseudo-fudge code, something like:

// if assembly/namespace of class being injected into is MyApp.ProjectFoo;
container.Register(typeof(IContext), typeof(FooContext));

// if assembly/namespace of class being injected into is MyApp.ProjectBar;
container.Register(typeof(IContext), typeof(BarContext));

Solution

  • This can be done using the RegisterConditional method:

    container.RegisterConditional<IContext, FooContext>(
        c => c.Consumer.ImplementationType.Assembly.Name.Contains("MyApp.ProjectFoo"));
    container.RegisterConditional<IContext, BarContext>(
        c => c.Consumer.ImplementationType.Assembly.Name.Contains("MyApp.ProjectBar"));
    

    If the check for the assembly name is a recurring pattern, you can extract this to a useful method:

    private static Predicate<PredicateContext> InAssembly(string assemblyName) =>
        c => c.Consumer.ImplementationType.Assembly.Name.Contains(assemblyName)
    

    You can use this method as follows

    container.RegisterConditional<IContext, FooContext>(InAssembly("MyApp.ProjectFoo"));
    container.RegisterConditional<IContext, BarContext>(InAssembly("MyApp.ProjectBar"));