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:

MsdnMefExample01

 

MsdnMefExample02

 

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,

MsdnMefExample03

 

… then you get this, or something like it:

MsdnMefExample04

(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:

MsdnMefExample05

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

MsdnMefExample06

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:

 

MsdnMefExample07

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:

MsdnMefExample08

MsdnMefExample09

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:

MsdnMefExample10

MsdnMefExample11

What happens if we haven’t defined an operator?

MsdnMefExample12

And finally a quick look at the _operations content:

MsdnMefExample13

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.

 

 

Advertisements