Override autofac registration with plugin

2020-06-09 03:42发布

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?

2条回答
我只想做你的唯一
2楼-- · 2020-06-09 04:23

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);
查看更多
够拽才男人
3楼-- · 2020-06-09 04:34

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

查看更多
登录 后发表回答