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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With