简体   繁体   中英

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

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM