2015-10-07 66 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)