first_page

MEF and Contract Names

On a great 2008 episode of DNRTV, Carl Franklin had Glenn Block screen-casting MEF coolness. Carl as usual asked the right question about why MEF uses strings (as well as types) to identify imports and exports. The answer that Glenn had was great for those of us who are working with the DLR. For the rest of us, we have another answer (that Glenn knows as well). We can see it in this attributed class declaration:

[Export("WordCommand", typeof(INamedItem))] public class GetFlatOpcCommand : IOfficeWordCommand

What is implied here is IOfficeWordCommand is derived from INamedItem. My ‘named item’ is just an object with a Name property. My intent is to import many named items. So the MEF Container can see ‘named items’ that are Office Word Commands or named items that are something completely different. So exporting the type INamedItem by itself could be ‘dangerous.’ There needs to be a way to constrain INamedItem in case another type in the Container besides IOfficeWordCommand implements it. There is a way: use a Contract Name.

I see something wrong with my Export attribute above. According to the MEF team my Contract Name should use namespaces to avoid ambiguity problems:

Note: By default a type should be passed for a contract, and not a string. Although contracts can be an arbitrary string this can lead to ambiguity. …For this reason if you do need to specify a string [contract], it is recommend that contract names should be qualified with a namespace that includes the Company Name for example Contoso.Exports.Sender.

So, perhaps, this is better:

[Export("Songhay.Office2010.WordWalkingStick.Commands.WordCommand", typeof(INamedItem))]
public class GetFlatOpcCommand : IOfficeWordCommand

A bit harder to read but definitely not ambiguous…

rasx()