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) –