Evil Wizard Example
This is a very simple example, nevertheless eligible to understand the basis of MEF.
Step 1. Add MEF to our Visual Studio solution
Adding MEF to your VS solution could not be easier. MEF is part of the .NET 4 Framework, so you can just Add a Reference as you would do with any .NET assembly: Into class EvilWizard add a reference to System.ComponentModel.Composition
Step 2. Define the EvilWizard as an Import Part
The next step is to tell MEF that our EvilWizard class is a part. Furthermore, it is an import that is going to consume a series of services, that is, is going to use a 'Hat service', a 'Robe service' and a collection of 'ISpell services'.
In order to do this, we will use MEF attribute based programming model, and we will decorate the EvilWizard components with the [Import] and [ImportMany] attributes as shown below:
If you have not guessed it yet, we use the [Import] attribute to represent a single service and [ImportMany] to represent a multiplicity of services. These attributes also represent default contracts, but we will deal with contracts in upcoming articles so do not worry for now.
Step 3. Define the Hat, Robe and Spells as Export Parts
We continue by defining the Hat, Robe and Spells as parts that provide services:
Notice how we used the [Export] attribute to decorate a class that provides a service and the [InheritedExport] attribute to decorate an interface and ensure that anything that implements that interface becomes a part.
Step 4. Discover The Parts and Setup The Container
Now that we have all the parts of our system ready, the next step consists in instantiating a catalog that will discover all parts within our assembly:
And passing this catalog to our MEF container so it will know which parts are available in our system:
Step 5. Let the magic happen
Finally, composing our evil wizard with other parts (hat, robe and spells) is as easy as:
And there we have our evil wizard kicking ass:
Step 6. Extending our RPG
Extending our RPG at this moment (for instance, adding new spells) would be as easy as adding new parts in a new assembly. We can use a [DirectoryCatalog ] instead of a [AssemblyCatalog ] to point to a path where we can drop all these new assemblies packed with new spells of destruction and mayhem.
As a final note, you can find the code sample at GitHub.