Discovered something interesting about MEF today when resolving exports and their associated metadata using custom attributes. Lets say you have two different types of metadata you want to strongly type by using 2 custom attributes and associated metadata interfaces like so:
In other words, the two sets of metadata expose the same sets of properties, but are differentiated by their strongly typed class representations. Now i expected that this meant i would be able to differentiate the two by requesting (importing) metadata of a certain type, for example the following would only retrieve library sections (ie UserControls decorated with the [LibrarySection] attribute):
It turns out however, that MEF is still using reflection behind the scenes to resolve the metadata, because it will resolve ANY UserControl that is decorated with either attribute, as both have the necessary properties allowing them to be mapped to either metadata type. This means that you need to differentiate the UserControls with a string identifier in both the attribute and the [Import] declaration to allow them to be differentiated when importing, like so:
This is unfortunate (if not a minor problem) because it dirties the consumption class with a magic string, but i dont see another way of achieving the same result when the exported types use contracts that match (in this example, all items exported as UserControls). This of course also holds true if you are trying to import types with metadata that is a subset of another metadata interface. For example if live views also had a Description property, then importing library sections would still match with live view UserControls because they provide the Title property necessary for MEF to resolve the library section metadata.