[英]How to export a class from an infrastructure library in MEF?
我有一个项目,其中包含两个模块,一个模块( Common
库)和Shell
。
请注意, Common
有一个FooService
,这有一个ExportAttribute
[Export]
public class FooService
{
}
并且这个应该由Module1
和Module2
,但是如果我具有ImportAttribute
,它将抛出错误。 请注意评论。
[ModuleExport("Module1.ModuleInit", typeof(Module1.ModuleInit))]
public class ModuleInit : IModule
{
private readonly IRegionManager _regionManager;
public IServiceLocator _serviceLocator;
// [Import(AllowRecomposition=true)]
public FooService _service;
[ImportingConstructor]
public ModuleInit(IRegionManager regionManager, IServiceLocator serviceLocator)
{
_regionManager = regionManager;
_serviceLocator = serviceLocator;
}
public void Initialize() { }
}
此代码与Module2
相同。
初始化模块'Module2.ModuleInit'时发生异常。 -异常消息为:组成保持不变。 更改由于以下错误而被拒绝:合成产生单个合成错误。 根本原因在下面提供。 查看CompositionException.Errors属性以获取更多详细信息。
1)发现多个出口与约束'(((exportDefinition.ContractName ==“ Common.FooService”)AndAlso(exportDefinition.Metadata.ContainsKey(“ ExportTypeIdentity”)AndAlso“ Common.FooService” .Equals(exportDefinition.Metadata .get_Item(“ ExportTypeIdentity”)))))'。
结果:无法在部分'Module1.ModuleInit'上设置导入'Module1.ModuleInit._service(ContractName =“ Common.FooService”)'。 元素:Module1.ModuleInit._service(ContractName =“ Common.FooService”)-> Module1.ModuleInit-> AssemblyCatalog(Assembly =“ Module1,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null”)
为什么我会收到此例外? 我只是导出一个对象。 我想知道正在发生什么以及如何解决。
请随时下载它,这是一个很小的项目。 下载紧凑型项目
这实际上应该只是一个评论,但是我没有足够的代表来做到这一点。 无论如何,在我看来,这就像一个范围界定的问题。 我相信MEF v1应该自动将导出视为单例,但我认为它在v2中已被逆转-不确定您使用的是哪个版本。 最近,我使用Microsoft.Composition(适用于MVC的MEF)遇到了一个问题,并通过使用HTTP请求级别作用域来获取整个请求期内的单个实例,从而解决了该问题。
[System.Composition.Export(typeof(ICustomDbContext))]
[System.Composition.Shared(Boundaries.HttpRequest)]
public class CustomDbContext : ICustomDbContext { ... }
解决方案:您遍历除 Shell Project 之外的每个项目,并查看参考资料。 请执行下列操作:
转到Bootstrapper类,添加以下内容:
protected override void ConfigureAggregateCatalog()
{
base.ConfigureAggregateCatalog();
// Add this assembly to the catalog.
this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Bootstrapper).Assembly));
// Add the FooService assembly
this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(FooService).Assembly));
}
然后取消注释模块中的[Import(AllowRecomposition)]和FooService。
在运行项目之前,需要转到Visual Studio菜单,选择“生成”->“清理项目”。 这将删除以前复制本地true的所有dll文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.