简体   繁体   English

根据程序集,使用Simple 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). 我有两个不同的IContext实现,它们存在于不同的程序集中(实际上它们位于不同的解决方案中)。 These assemblies are both used in a single parent project. 这些程序集都在单个父项目中使用。 This parent project uses SimpleInjector for DI. 这个父项目使用SimpleInjector进行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?. 有没有办法让Simple Injector根据被注入的类的程序集位置注入/注册不同的实现?

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: 这可以使用RegisterConditional方法完成:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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