I’m looking to use MEF for a plugin system for an application I’m building. Each component I want to have an identifier on (a GUID) which I want to be able to look up against. But this ID is also something that is useful when working with the exported part.
Is there a way that I can have a Metadata attribute which contains the ID as well as a property (or method) on the exported part, short of having developers fill it out twice or use reflection to find it from the attribute?
It’s likely to be a mixture of a MEF metadata attribute, and an abstract base class. I would define my plugin contract as something like:
I’ve enforced that the
IPlugininterface also inherits our metadata contractIPluginMetadata. Next, we can create a custom export attribute:You don’t need to decorate the export attribute with the metadata contract
IPluginMetadata, as MEF will project the properties anyway, but I prefer to do so, so if I do introduce changes to my metadata contract, then my export attribute should be updated too. No harm, no foul.Once we’ve done this, we can define an abstract base class from which to implement our plugin contract:
We can then grab the custom attribute through the abstract class’s constructor, and apply the property accordingly. That we can do:
And also:
We can see that out
PluginIdis exposed both through exported metadata, as well as a property of our plugin.That code is all untested, but I hope it pushes you in the right direction.