MEF 2.0 – mini series: part 3 (Fluent import constructor)
this is the 3rd post in the MEF 2.0 mini series.
you can see the following TOC for other posts in this series.
in this post I will discuss the fluent constructor injection API.
the following code is having a Logger and Worker class which is having 2 constructor (one has no parameters and the other is getting ILogger):
the question is, which of the construction will be invoked by the following code?
the code Export the Logger and the Worker but doesn’t define explicitly which of the Worker’s construction should be invoke.
the answer is that it will invoke the constructor that is getting the ILogger parameter, but could we be more precise?
actually we do have 2 different options.
first option is to use SelectConstructor before the Export method.
see the following code:
this way we can define an expression that define which constructor should be invoke.
the expression is getting a ParameterImportBuilder which I used to define the logger (builder.Import<ILogger>()).
the next option is to set the SelectConstructor after the Export.
now we are getting a ConstructorInfo and we can select a single constructor out of this array.
the code select a constructor which is having a single parameter, but the real implementation is up to you. you can ask on whatever constructor’s aspect which you like to.
as cool as it is to control the constructor injection using the fluent API,
you may consider to use imported properties rather than constructor injection because it can be more stable is during the composition state and can apply on more scenarios, including implementation of IPartImportsSatisfiedNotification.