How to Inject Dependencies to Dynamically Loaded Assemblies

 ̄綄美尐妖づ 提交于 2020-04-10 18:07:21

问题


I have a manager class that loads various plug-in modules contained in separate assemblies through reflection. This modules are communication to the outside world (WebAPI, various other web protocols).

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

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

These plug-in modules must communicate with an object contained within the manager class. How can I implement this? I thought about using dependency injection/IoC container, but how can I do this across assemblies?

Another thought that I had, that I am not thrilled with, is to have the modules reference a static class containing the resource that they need.

I appreciate any constructive comments/suggestions.


回答1:


Most ioc containers should support this. For example, with autofac you might do:

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

Depending on how the rest of your app will call the plugins, you can alter the registrations appropriately (e. g. register with AsImplementedInterfaces() to retrieve the plugin by a known interface or Keyed to retrieve the plugin by some key object (e. g. a string)).



来源:https://stackoverflow.com/questions/20693427/how-to-inject-dependencies-to-dynamically-loaded-assemblies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!