【问题标题】:MEF import doesn't work with external assemblyMEF 导入不适用于外部程序集
【发布时间】:2015-10-13 19:55:05
【问题描述】:

我有以下 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),我会收到“此字符串已导入”消息框,但我会收到“找不到类”信息。 行为差异的任何原因?我是不是做错了什么?

【问题讨论】:

  • 您需要确保使用 same 接口进行导出。 string 来自 mscorlib 的 ist,但如果 app.exe 中有 IString,ClassLibrary.dll 中有 IString,它们是 MEF 的不同接口。
  • 那么我如何告诉MEF应用程序中声明的IString与dll中声明的IString相同?
  • 将应用添加为引用并使用引用的 IString 接口。 (或者使用从应用程序和库中引用的单独的 Interfaces.dll)
  • 感谢您的帮助

标签: c# .net mef


【解决方案1】:

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

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

当然有可能做到这一点,例如使用托管插件框架。有关两者的更多信息,请参阅此帖子:Choosing between MEF and MAF (System.AddIn)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 2013-08-24
    • 2018-11-29
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多