I am trying to use MEF conventions within the .NET Framework 4.5 and am stuck on something I thought should be simple.
I want to export a set of classes and all are working except for the one that has more than one constructor so MEF by default calls the constructor with the most parameters which is causing a break as the parameters are aren't importing which is how it should be I guess.
Anyway, I want to make sure it works by telling MEF to export the constructor with no parameters.
var registration = new RegistrationBuilder();
registration.ForTypesDerivedFrom<TestStepResult>()
.Export<TestStepResult>()
.SelectConstructor(xxx);
So I know I need to do something in the SelectConstructor but cannot find what should be there to say to call the constructor with no parameters.
One way to do this is:
registration.ForTypesDerivedFrom<TestStepResult>()
.Export<TestStepResult>()
.SelectConstructor(ctorInfos =>
{
var parameterLessCtor = ctorInfos.FirstOrDefault(ci => ci.GetParameters().Length == 0);
if (parameterLessCtor != null)
return parameterLessCtor;
else
return ctorInfos.First();
});
Note that it include some simple error handling. If there is no parameterless .ctor it returns the first one available. This might not be what you need though. You will have to decide on how to handle this case.