存储库<t>的MEF导出:IRepository <t> </t> </t>

时间:2010-06-23 07:51:52

标签: c# generics mef

我正在尝试使用MEF导出以下内容:

[Export(typeof(IRepository<>))]
public class Repository<T> : IRepository<T>
    where T : class
{

导入

[Import(typeof(IRepository<>))]
private IRepository<Contact> repository;

但是在撰写MEF时,我一直收到错误信息:

=========================================

构图保持不变。由于以下错误,更改被拒绝:组合产生单个组合错误。根本原因如下。查看CompositionException.Errors属性以获取更多详细信息。

1)没有找到符合约束'((exportDefinition.ContractName =“Interfaces.IRepository()”)&amp;&amp;(exportDefinition.Metadata.ContainsKey(“ExportTypeIdentity”)&amp;&amp;&amp;&amp;&amp; .IRepository()“。Equals(exportDefinition.Metadata.get_Item(”ExportTypeIdentity“))))',无效导出可能已被拒绝。

导致:无法在“SoCLINQ2SQL.RepositoryTest”部分设置导入'SoCLINQ2SQL.RepositoryTest.repository(ContractName =“Interfaces.IRepository()”)'。 元素:SoCLINQ2SQL.RepositoryTest.repository(ContractName =“Interfaces.IRepository()”) - &gt; SoCLINQ2SQL.RepositoryTest

3 个答案:

答案 0 :(得分:3)

据我所知,根据Glenn Block's post关于这个问题,MEF不支持“开箱即用”的开放式通用类型。

显然MEF contrib project中有对它的支持。

我相信在这种情况下,您可以将导出保留为开放式通用类型,但在导入方面,您需要将导入更改为:

[Import(typeof(IRepository<Contact>))]
private IRepository<Contact> repository;

答案 1 :(得分:1)

我遇到了类似的问题,它与将程序集添加到 AggregateCatalog 的顺序有关。下面的示例说明了 Bootstrapper.ConfigureAggregateCatalog()“模块B”“模块C”调用服务,但“模块C”未添加到 AggregatorCatalog 。我只需要改变顺序,它就解决了问题。

    protected override void ConfigureAggregateCatalog()
    {
        base.ConfigureAggregateCatalog();


 // Be aware of the order on which the assemblies are added to the AggregateCatalog.
 // It's important to add the assembly to the AggregateCatalog in the correct order, otherwise
 // you may get the error "No valid exports were found that match the constraint".
 // In the example below, if Module B invokes a method of Module C, module C must be
 // added to the AggregateCatalog prior to Module B. 
 // Please note the Bootstrapper assembly also needs to be added to the AggregateCatalog.
 // -------------------------------------------------------------------------------------- 
        this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Bootstrapper).Assembly));
        this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(ModuleA).Assembly));
        this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(ModuleC).Assembly));
        this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(ModuleB).Assembly));

    }

答案 2 :(得分:0)