2015-10-07 67 views
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」消息。 任何行爲差異的原因?難道我做錯了什麼?

+0

您需要確保您使用*相同*接口進行導出。 mscorlib中的'string' ist,但是如果app.exe中的IString和ClassLibrary.dll中的IString,它們是MEF的不同接口。 –

+0

那麼如何告訴MEF在應用程序中聲明的IString與在dll中聲明的IString相同? – user2852294

+0

添加該應用程序作爲參考,並使用引用的IString接口。 (或使用從應用程序和庫中引用的單獨的Interfaces.dll) –

回答

2

爲了完成的緣故,我會發布答案。

使用MEF時,需要注意使用完全相同的類型,也就是說,來自同一個程序集的相同類型。這就是爲什麼MEF並不是真正有用的插件系統,因爲每次重建包含接口的程序集時,都需要重新編譯每個插件。

當然有可能做到這一點,例如使用託管AddIn框架。看到這篇文章的更多信息都:Choosing between MEF and MAF (System.AddIn)