问题
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