16

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

现在我想允许IFoo在插件程序集中实现的替代实现,它可以放在“插件”文件夹中。如果存在,我如何配置 autofac 以更喜欢这种替代实现?

4

2 回答 2

19

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

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

查看默认注册

于 2013-04-02T03:18:27.293 回答
1

正如 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<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);
于 2013-04-03T12:47:30.597 回答