繁体   English   中英

MEF导入不适用于外部装配

[英]MEF import doesn't work with external assembly

我有以下MEF测试代码:

[Import(AllowDefault = true)]
string importedString; 

[Import(typeof(IString), AllowDefault = true)]
public IString importedClass;

private void Import(bool fromDll)
{
    CompositionContainer MyContainer;
     if (fromDll)
    {
        DirectoryCatalog MyCatalog = new DirectoryCatalog("D:\\Source\\ClassLibrary\\bin\\Debug\\", "ClassLibrary.dll");
        MyContainer = new CompositionContainer(MyCatalog);
    }
    else
    {
        AssemblyCatalog MyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
        MyContainer = new CompositionContainer(MyCatalog);
    }
    MyContainer.SatisfyImportsOnce(this);

    MessageBox.Show(importedString == null ? "String not found" : importedString, "fromDLL=" + fromDll.ToString());
    MessageBox.Show(importedClass == null ? "Class not found" : importedClass.getClassMessage(), "fromDLL=" + fromDll.ToString());
}

导出部分在同一文件中定义,如下所示:

public class MyString
{
    [Export()]
    public string message = "This string is imported";
}

public interface IString
{
    string getClassMessage();
}

[Export(typeof(IString))]
public class MyClass : IString
{
    public string getClassMessage()
    {
        return ("This class is imported");
    }
}

现在,如果我调用Import(false),一切正常,我确实得到两个带有文本“此字符串已导入”和“此类已导入”的消息框

但是,如果我创建ClassLibrary.dll(在其名称空间中仅具有导出的部分)并调用Import(true),则会收到“此字符串已导入”消息框,但会收到“找不到类”消息。 行为不同的任何原因? 难道我做错了什么?

为了完整起见,我将发布答案。

使用MEF时,需要注意使用的是完全相同的类型,即相同的程序集中的相同类型。 这就是为什么MEF不能真正用作插件系统的原因,因为每次重建包含接口的程序集时,都需要针对该接口重建每个插件。

当然,也可以执行此操作,例如使用Managed AddIn Framework。 有关这两者的更多信息,请参见此帖子: 在MEF和MAF之间选择(System.AddIn)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM