joe*_*975 6 c# reflection dependency-injection ioc-container
我有一个管理器类,它通过反射加载包含在单独程序集中的各种插件模块。这些模块与外部世界(WebAPI,各种其他网络协议)进行通信。
public class Manager
{
public ILogger Logger; // Modules need to access this.
private void LoadAssemblies()
{
// Load assemblies through reflection.
}
}
Run Code Online (Sandbox Code Playgroud)
这些插件模块必须与包含在管理器类中的对象通信。我该如何实施?我想过使用依赖注入/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);
Run Code Online (Sandbox Code Playgroud)
根据应用程序的其余部分如何调用插件,您可以适当地更改注册(例如,使用 AsImplementedInterfaces() 注册以通过已知接口检索插件,或使用 Keyed 注册以通过某些关键对象(例如字符串)检索插件) 。