【发布时间】: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)
-
感谢您的帮助