MEF 2.0 – mini series: part 4 (Fluent Import)
this is the 4th 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 import API.
we was talking about Fluent Export and Constructor Injection in the previous posts. this post will complete the main scenarios of Import’s fluent API.
I will demonstrate the import technique using the following classes:
we can Export both classes by one of the fluent techniques which we discuss in previous posts, for example:
but this is not enough, because Foo’s Log property has no [Import] attribute, therefore it will be ignored by the composition.
using the fluent ImportProperties, you can introduce it into the composition :
the property’s Type is referred by the generics parameter while the Lambda used for filtering the target properties.
actually you can take it further and configure the import behaviors.
for example you can set the import to Allow Default:
it’s consider as best practice to Allow Default and implement IPartImportsSatisfiedNotification interface which is an interception point which occurs right after the composition.
the idea is to check the composition state within the OnImportsSatisfied()
method in order to verify the composition state.
It is true that MEF exceptions have made better, but it still not perfect and sometimes it is really hard to trace the root cause of the exception. implementation of IPartImportsSatisfiedNotification will make the tracing easier.
so what about Select Many?
let change our Foo class to the following code:
the following code will define the Log property as [ImportMany]:
as you can see we are using the same overload that can manipulate the Import’s behaviors.
by the same technique you can define a re-composition and the creation policy:
fluent Import is complimentary to fluent Export.
it’s fairly flexible API which enable to assign your own or 3rd party class’s properties.
actually you can take a 3rd party class and inject it’s public properties through those techniques.