簡體   English   中英

根據程序集,使用Simple Injector注入不同的依賴項

[英]Injecting different dependencies with Simple Injector depending on assembly

我有兩個不同的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));

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM