Override autofac registration with plugin

半世苍凉 提交于 2019-12-21 03:32:09

问题


I have an IFoo service implemented by DefaultFoo, and I've registered it as such in my autofac container.

Now I would like to allow for an alternative implementation of IFoo to be implemented in a plugin assembly, which can be dropped in a "plugins" folder. How do I configure autofac to prefer this alternative implementation if it is present?


回答1:


If you register some interface implementations, Autofac will use the latest registration. Other registrations will be overridden. In your case, Autofac will use the plugin registration, if plugin exists and register own IFoo service implementation.

If more than one component exposes the same service, Autofac will use the last registered component as the default provider of that service.

See Default Registrations




回答2:


As stated by Memoizer, the latest registration overrides earlier ones. I ended up with something like this:

// gather plugin assemblies
string applicationPath = Path.GetDirectoryName(
    Assembly.GetEntryAssembly().Location);
string pluginsPath = Path.Combine(applicationPath, "plugins");
Assembly[] pluginAssemblies = 
    Directory.EnumerateFiles(pluginsPath, "*.dll")
    .Select(path => Assembly.LoadFile(path))
    .ToArray();

// register types
var builder = new ContainerBuilder();
builder.Register<IFoo>(context => new DefaultFoo());
builder.RegisterAssemblyTypes(pluginAssemblies)
    .Where(type => type.IsAssignableTo<IFoo>())
    .As<IFoo>();

// test which IFoo implementation is selected
var container = builder.Build();
IFoo foo = container.Resolve<IFoo>();
Console.WriteLine(foo.GetType().FullName);


来源:https://stackoverflow.com/questions/15754702/override-autofac-registration-with-plugin

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