如何将依赖项注入动态加载的程序集 [英] How to Inject Dependencies to Dynamically Loaded Assemblies
问题描述
我有一个manager类,该类通过反射来加载包含在单独的程序集中的各种插件模块。该模块与外界通信(WebAPI,各种其他Web协议)。
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.
}
}
这些插件模块必须与包含的对象通信在经理班内。我该如何实施?我曾考虑过使用依赖注入/ IoC容器,但是如何在程序集之间做到这一点呢?
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.
推荐答案
大多数ioc容器应支持此功能。例如,使用autofac,您可以执行以下操作:
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);
根据应用程序其余部分如何调用插件,您可以适当地更改注册(例如向AsImplementedInterfaces()注册以通过已知接口检索插件,或通过Key键通过某些关键对象(例如字符串)检索插件。)
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)).
这篇关于如何将依赖项注入动态加载的程序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!