【发布时间】:2015-06-22 15:49:50
【问题描述】:
根据http://docs.autofac.org/en/latest/integration/mef.html 的文档使用时,Mef CompositionContainer 无法解析 Autofac 依赖项。
我有一个大型代码库,它广泛使用了 ServiceLocator 和单例...服务定位器通过使用缓存的 System.ComponentModel.Composition.Hosting.CompositionContainer 来完成所有对象创建、组合等。 (另外,请注意我们目前使用/需要元数据支持)我正在尝试从这个切换到更现代的架构。为此,现有的基于 Mef(基于“CompositionContainer”)的服务定位器必须与 Autofac IoC 容器合作。
下面的函数
- 创建一个 Mef
CompositionContainer - 证明 MEF 能够解析简单的导出
- 将 Autofac 配置为向 MEF 注册并使用
.Exported扩展方法将AutofacExport导出到 MEF。 - 证明 Autofac 可以使用 Autofac 中定义的依赖关系解析 mef 组件
- 表明 Mef 无法解析带有 Autofac 依赖项的导出组件组件。
抛出的异常是:ImportCardinalityMismatchException("No exports were found that match the constraint: ContractName MefExportWithDependency RequiredTypeIdentity MefExportWithDependency" 被抛出。
public void MefResolve_ObjectWithDependency_CanResolveWhenAutofacRegistersDependeyncy2()
{
//1. Initialize Mef
var composablePartCatalogs = new List<ComposablePartCatalog>
{
new AssemblyCatalog(Assembly.GetExecutingAssembly())
//A lot more here..
};
var aggregateCatalog = new AggregateCatalog(composablePartCatalogs);
var container = new CompositionContainer(aggregateCatalog, true);
//2. As expected this is resolved
container.GetExport<MefExport>().Should().NotBeNull();
//3. Initialize Autofac
var builder = new ContainerBuilder();
builder.Register(c => new AutofacExport()).Exported(x => x.As<AutofacExport>());
builder.RegisterComposablePartCatalog(aggregateCatalog);
var ioc = builder.Build();
//4. Here Autofac is correctly providing the dependency to the mef ImportingConstructor
ioc.Resolve<MefExportWithDependency>().AutofacExport.Should().NotBeNull();
//5. The next line will throw ImportCardinalityMismatchException
container.GetExport<MefExportWithDependency>();
}
上面的代码需要定义以下类:
public class AutofacExport { }
[Export]
public class MefExport { }
[Export]
public class MefExportWithDependency
{
public AutofacExport AutofacExport { get; set; }
[ImportingConstructor]
public MefExportWithDependency(AutofacExport autofacExport)
{
AutofacExport = autofacExport;
}
}
注意: 我还查看了https://www.nuget.org/packages/MefContrib.Integration.Autofac/ - 它承诺将 Mef 与 Autofac 集成。但是,我找不到有关如何配置它的相关文档,并且该软件包没有太多用途。
【问题讨论】: