1
我有以下MEF测试代码: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");
}
}
现在每一件事作品罚款如果我打电话导入(false),我得到两个消息框文本“此字符串导入”和“此类导入”
但是,如果我创建ClassLibrary.dll(其中只有导出sectio n在它的名字空间)并调用导入(true),我得到“这个字符串被导入”消息框,但是我得到了“Class not found”消息。 任何行为差异的原因?难道我做错了什么?
您需要确保您使用*相同*接口进行导出。 mscorlib中的'string' ist,但是如果app.exe中的IString和ClassLibrary.dll中的IString,它们是MEF的不同接口。 –
那么如何告诉MEF在应用程序中声明的IString与在dll中声明的IString相同? – user2852294
添加该应用程序作为参考,并使用引用的IString接口。 (或使用从应用程序和库中引用的单独的Interfaces.dll) –