【问题标题】:Injecting different dependencies with Simple Injector depending on assembly根据程序集使用 Simple Injector 注入不同的依赖项
【发布时间】:2016-05-11 22:50:44
【问题描述】:

我有两个不同的IContext 实现在不同的程序集中(实际上它们在不同的解决方案中)。这些程序集都在一个父项目中使用。此父项目使用 SimpleInjector 进行 DI。

有没有办法让 Simple Injector 根据被注入的类的装配位置来注入/注册不同的实现?

在伪软糖代码中,类似于:

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

【问题讨论】:

    标签: c# dependency-injection simple-injector


    【解决方案1】:

    这可以使用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"));
    

    如果对程序集名称的检查是一个循环模式,您可以将其提取为一个有用的方法:

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

    您可以按如下方式使用此方法

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

    【讨论】:

      猜你喜欢
      • 2017-06-18
      • 1970-01-01
      • 2015-04-02
      • 2016-09-01
      • 2013-04-01
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 2015-11-01
      相关资源
      最近更新 更多