MEF Supports metadata to be passed in addition to Contracts. As we have already discussed some of the interesting catalogs present in MEF base class library, lets take a look how metadata can be transferred in the MEF system. We generally use MetaData to determine something regarding the type. Probably when the actual object is unavailable. Lazy implementation is the ideal scenario when use of MetaData is often required.
MEF shares metadata in terms of a special attribute named ExportMetadataAttribute. This attribute supports a Key value collection where the key is specified as string and the value is an object. While dealing with UserInterface we often use Metadata to determine where exactly the plugin interface needs to be loaded.
The Caveats of Metadata is such that the Exporter exports the metadata information about the type from it, and the importer can look into the metadata even though the actual object does not exists or created (using Lazy).
Lets look how to work with Metadata:
[Export] [ExportMetadata("Name", "Plugin from Plugin2")] public string GetName() { this.ExportName = "Plugin from Plugin2"; if (this.MyActionDelegate != null) this.MyActionDelegate(this.ExportName); return this.ExportName; }
Thus you can see the Plugin is exporting a string value called Name as Metadata. Now when the object is imported, you can get the Metadata information from ImportDefinations.
DirectoryCatalog dcatalog = new DirectoryCatalog("plugins", "*.dll"); AssemblyCatalog acatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); AggregateCatalog catalog = new AggregateCatalog(dcatalog, acatalog); PluginHost host = new PluginHost(); CompositionContainer container = new CompositionContainer(catalog); container.ComposeParts(host); foreach (var part in catalog.Parts) Console.WriteLine(part.Metadata["Name"]); Console.ReadKey(true);
MEF also has another implementation of getting Metadata informations easily. When importing objects in Lazy implementation you can directly add the Metadata type and the object will automatically created by the MEF framework.
[ImportMany] public IEnumerable, string>> GetNames { get; set; }
The second type argument specifies the Metadata type information.
I hope this post comes handy.
Read more about it from the links :
Managed Extensibility Framework – A Look
Steps to write a plugin based application with MEF
Thank you for reading.