Override autofac registration with plugin

孤街醉人 提交于 2019-12-03 10:31:16
Memoizer

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

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