MEF Composition .NET 4.0

时间:2012-06-25 12:49:07

标签: mef

预先感谢您的协助。我有以下导出部分:

[Export (typeof(INewComponent))]  // orignally tried just [Export} here and importing NewComponent below
public class NewComponent : INewComponent  
{  
    // does stuff including an import  
}

Console测试程序导入上述内容:

public class Program   
{    

    [Import]  // have tried variations on importing "NewComponent NewComponent" etc  
    public INewComponent NewComponent
    {
        get;
        set;
    }

    public static void Main(string[] args)
    {
        var p = new Program();
        var catalog = new AssemblyCatalog(typeof(Program).Assembly);
        var container = new CompositionContainer(catalog);
        container.ComposeParts(p);
}

使用这些CompositionExceptions组合失败(我删除了名称空间以保护内疚:)):

  

1)未找到与约束匹配的有效导出   '((exportDefinition.ContractName ==“INewComponent”)AndAlso   (exportDefinition.Metadata.ContainsKey(“ExportTypeIdentity”)AndAlso   “INewComponent” .Equals(exportDefinition.Metadata.get_Item( “ExportTypeIdentity”))))”,   无效的出口可能已被拒绝。

如果我在主程序中执行这样的合成,则合成成功:

public class Program  
{      

    public static void Main(string[] args)
    {
        INewComponent newComponent = new NewComponent();

        var catalog = new AssemblyCatalog(typeof(Program).Assembly);
        var container = new CompositionContainer(catalog);
        container.ComposeParts(newComponent);
    }
}

谢谢

2 个答案:

答案 0 :(得分:3)

您的导出部分是否与Program包含在同一个程序集中?如果它位于单独的DLL中,则还需要在目录中包含该程序集,如下所示:

var aggregateCatalog = new AggregateCatalog();
aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly));
aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(NewComponent).Assembly));
var container = new CompositionContainer(aggregateCatalog);
// etc...

如果这不起作用,那么有一个很好的开源工具,名为Visual MEFx,可以帮助您分析您的目录。这是一篇关于设置它的简短文章:

Getting Started With Visual MEFx

答案 1 :(得分:2)

NewComponent课程中你写了这个:

// does stuff including an import

如果未显示导入存在问题,那么MEF会抱怨Program.NewComponent导入而不是实际更深层次的导入。这被称为"稳定的组合"。 Stable composition can be useful,但it also complicates the debugging of a failed composition

您可以按照MEF文档中有关Diagnosing Composition Errors的说明,了解实际原因。

在一个小程序中,您还可以尝试调用container.GetExportedValue<ISomeExport>()进行一些导出,直到找到导致问题的导出为止。