I have the following MEF test code:
[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());
}
The export section is defined in the same file as follows:
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");
}
}
Now every thing works fine if I call Import(false), I do get two message boxes with the text "This string is imported" and "This class is imported"
However, if I create the ClassLibrary.dll (Which just has the exported section in its namespace) and call Import(true), I do get "This string is imported" message box but I get the "Class not found" message. Any reason for the difference in behavior? Am I doing something wrong?
For completion's sake I'll post the answer.
When using MEF, you need to watch out that you use the exact same types, which means, the same type from the same assembly. This is why MEF is not really useful as a plugin-system, because every time you rebuild the assembly containing the interfaces, you need to rebuild every plugin against that.
There are possibilities to do this of course, for example using the Managed AddIn Framework. See this post for more info on both: Choosing between MEF and MAF (System.AddIn)