I have more or less the same problem as in this question: C#/MEF doesn't work with a base class without parameterless constructor
I understand the answer as well. MEF doesn't know a value for val so its not able to create an instance.
But I have no base ctor call and a default value for val:
[Export(typeof(IPrimitiveDecomposer))]
public class Prim : IPrimitiveDecomposer
{
[ImportingConstructor]
public Prim(int val=0)
{//some code
}
public bool Match(Node node) {return true;}
}
The code compiles fine, but MEF doesn't seem to have an export for IPrimitiveDecomposer when I ask for it. When I do the following all works fine:
[Export(typeof(IPrimitiveDecomposer))]
public class Prim : IPrimitiveDecomposer
{
public Prim() : this(0)
public Prim(int val=0)
{//some code
}
public bool Match(Node node) {return true;}
}
thx for your help Soko
Optional arguments in C# are a compile time "trick". The constructor generated by your first code does not have a parameterless constructor. Instead, it has a constructor which takes one integer, and which is decorated with attributes to provide the default value. It's effectively like writing:
public Prim([Optional, DefaultParameterValue(0)] int val)
{
The C# compiler knows about these attributes, and will "fill in" the value at compile time when it finds a method or constructor requiring this information.
MEF does not look for these attributes. It requires a default constructor, or a constructor where each of the arguments is provided by composed types. Your first version fails in this case, so MEF can't construct the type.
Using two constructors, as you showed, is the correct way to handle this with MEF.