Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override autofac registration with plugin

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?

like image 326
Wim Coenen Avatar asked Apr 02 '13 01:04

Wim Coenen


2 Answers

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

like image 173
Memoizer Avatar answered Sep 20 '22 11:09

Memoizer


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);
like image 21
Wim Coenen Avatar answered Sep 19 '22 11:09

Wim Coenen