1
votes

How can I use MEF to dynamically resolve my imports. One Example:

class Class1
{
    [Export("P1", typeof(string)]
    string _p1;
}

class Class2
{
    [Import("P1", typeof(string), AllowRecomposition = true]
    string importedP1;
}

Class1 is in one assembly and Class2 in another. The assemblies don't know each other. The problem is that on a call of CompositionContainer.ComposeParts() the assembly/export of Class1 is not registered in any Catalog but the import of Class2. Basically I can't even make sure that the assembly of Class1 will ever be loaded. But if it would be loaded I would like that the Import will be satisfied automatically/dynamically.

How can I achieve this? I thought "AllowRecomposition" is exactly for this case but I am getting a ChangeRejectedException because a composition error occured with the message that no valid export was found with the restrictions of my import.

2

2 Answers

2
votes

You should set AllowDefault=true in your Import declaration. This way, you won't get a runtime error if the import wasn't satisfied, and you'll still be able to satisfy it if the assembly is loaded later.

[Import("P1", typeof(string), AllowDefault = true, AllowRecomposition = true]
0
votes

check the MEF documentation. the problem is that MEF has to instantiate both - class1 and class2 otherwise you did not get it work.

you can post your code for the compositioncontainer and using of class1,class2 so we can help you a little better. one way is to set the [Export] attribute to your classes.