MEF 2.0 – mini series: part 2 (Fluent and Conventional Export)
this is the second post in the MEF 2.0 mini series.
you can see the following TOC for more.
in this post I will start to cover the fluent discovery model and the idea of discovery by convention.
traditionally, out of the box, MEF come with a single discovery model, which was the Attribute model.
it is true that you could extend MEF’s discovery model by using either a custom catalog or a custom export provider, but this task wasn’t as simple as the MEF 2 fluent discovery model and therefore wasn’t a common practice.
MEF 2.0 is having the new RegistrationBuilder class which can be used to apply a custom picker (filter) for specific types within the scope of a catalog.
the idea is that the catalog will apply a sandbox which is a searching area scope (like Assembly, Directory, ext…), while the registration builder will pick up the relevant exported part within the scope.
actually the catalog will compose both the old attribute model and the picked up types.
this technique can be used either as a replacement for the Attribute model or as a complementary for 3rd party types which we cannot recompile with the [Export] attribute.
in order to work with the registration builder, you should add reference to
at its simplest form it can be used to append a specific type into the composition.
the above code exporting the AesManaged cryptography algorithm as a symmetric crypto algorithm.
currently the Import is still using the old Attribute model. I will show you how to define a fluent Imports in future post.
another aspect that you can control is the instantiation strategy by using the SetCreationPolicy:
in future post I will talk about creation scope and lifetime, which is a fine tuning option for the part lifetime control.
you can choose to export anything that derived from a Type or implement an Interface:
Export by conventions
a common IoC strategy is to discover extensions by convention.
for example loading all the type with a ‘Plugin’ suffix.
this strategy reduce the maintenance of either xml files or bootstrapper code.
this type of discovery made easy in MEF 2.0.
the following code is loading any type which is ending with a ‘Plugin’ extension into the composition.
as you can see that the code is exporting all of the interfaces that was implemented by the plugins.
foe example, if you are having the following interfaces and implementation:
LoggerPlugin will be export as ILogPlugin and FilePlugin will be export as ISavePlugin.
ExportInterfaces is having a few overloads which you can use to refine the interface exporting, instead of exporting all of the implemented interfaces, you can define a convention, for example:
MEF 2.0 fluent and conventional model is a great improvement over the Attribute model. as you can see you can use both model together, but the convention model can ease your maintenance.
in the next post I will discuss it further.