MEF, Herding Code

This is a nice simple trip down MEF Lane. As is this, on MSDN.

Actually, I think I prefer the MSDN one:





Key things to note from above:

The name of the concrete implementation doesn’t matter: Program is just looking to import anything that satisfies the ICalculator contract. But if in the namespace you add a second concrete implementation called eg MySimpleCalculator2,



… then you get this, or something like it:


(But if you have just the one concrete implementation matching the interface, then all is good, to reiterate that)

The article has the full detail, but we can then go on to implement the calculator to have some meaning. Add in the interfaces for IOperation and IOperationData:


Now we’ve defined those, the Calculator implementation will recognise this:


Worth repeating what MSDN says about that:

Lazy<T, TMetadata> is a type provided by MEF to hold indirect references to exports. Here, in addition to the exported object itself, you also get export metadata, or information that describes the exported object. Each Lazy<T, TMetadata> contains an IOperation object, representing an actual operation, and an IOperationData object, representing its metadata.

We define an Add implementation class for IOperation which also uses an ExportMetadata decoration to implicitly create a Symbol / + class:



Finally, there is just the Calculate method to enhance – my example assumes that the user will always enter data in the format “22(space)+(space)55”, and never make a mistake in doing that:



Do the same for subtract. Notice that there is no reference to any classes actually called add or subtract, just anything which satisfies the interface and the symbol requirement:



What happens if we haven’t defined an operator?


And finally a quick look at the _operations content:


The podcast site Herding Code manages to get in some good people. This is Rob Ashton… who seems to be pretty selfless, based on his blurb about coding for free.