使用插件覆盖autofac注册

我有一个由DefaultFoo实现的IFoo服务,我已经在我的autofac容器中注册了它。

现在我想允许在插件程序集中实现IFoo的替代实现,可以将其放在“plugins”文件夹中。 如果存在,如何配置autofac以优先选择此替代实现?

如果您注册了一些接口实现,Autofac将使用最新的注册。 其他注册将被覆盖。 在您的情况下,如果插件存在并且注册自己的IFoo服务实现,Autofac将使用插件注册。

如果多个组件公开相同的服务,Autofac将使用最后一个注册的组件作为该服务的默认提供程序。

请参阅默认注册

正如Memoizer所述,最新的注册覆盖了之前的注册。 我最终得到了这样的东西:

 // 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(context => new DefaultFoo()); builder.RegisterAssemblyTypes(pluginAssemblies) .Where(type => type.IsAssignableTo()) .As(); // test which IFoo implementation is selected var container = builder.Build(); IFoo foo = container.Resolve(); Console.WriteLine(foo.GetType().FullName);