簡體   English   中英

如何為動態加載的程序集注入依賴項

[英]How to Inject Dependencies to Dynamically Loaded Assemblies

我有一個管理器類,通過反射加載包含在單獨程序集中的各種插件模塊。 這些模塊是與外界的通信(WebAPI,各種其他Web協議)。

public class Manager
{
   public ILogger Logger; // Modules need to access this.

   private void LoadAssemblies()
   {
     // Load assemblies through reflection.
   }
}

這些插件模塊必須與manager類中包含的對象進行通信。 我該如何實現呢? 我考慮過使用依賴注入/ IoC容器,但是如何在程序集中執行此操作?

我對此感到興奮的另一個想法是讓模塊引用一個包含所需資源的靜態類。

我感謝任何建設性的意見/建議。

大多數ioc容器應該支持這一點。 例如,使用autofac,您可以執行以下操作:

// in another assembly
class plugin {
   // take in required services in the constructor
   public plugin(ILogger logger) { ... }
}

var cb = new ContainerBuilder();

// register services which the plugins will depend on
cb.Register(cc => new Logger()).As<ILogger>();

var types = // load types
foreach (var type in types) {
    cb.RegisterType(type); // logger will be injected
}

var container = cb.Build();
// to retrieve instances of the plugin
var plugin = cb.Resolve(pluginType);

根據應用程序的其余部分將如何調用插件,您可以適當地更改注冊(例如,使用AsImplementedInterfaces()注冊以通過已知接口檢索插件或使用Keyed通過某個關鍵對象(例如字符串)檢索插件) 。

暫無
暫無

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

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