Search code examples
c#mef

Referencing ExportMetaData from within MEF-part?


This might be a super simple question, but since Google has a hard time giving me answers you might!

I'm wondering if its possible for a part in MEF to get hold of values defined in its own ExportMetadata?

Lets say I got this code for a part:

[ExportMetadata("name", "A Template Plugin")]
[ExportMetadata("guid", "0db79a169xy741229a1b558a07867d60")]
[ExportMetadata("description", "A template for a new plugin")]
[ExportMetadata("version", "1.0.0.43")]
[Export(typeof(IPlugin)), PartCreationPolicy(CreationPolicy.NonShared)]

public class PluginExport : IPlugin, IDisposable
    {
  ... code goes here...
... can I get hold of metadata, ie the "guid" key ??? ...
}

If anyone questions the sanity of this its bcause Im making a plugin template for 3pp developers and some values (not shown in the example above) also needs to be used from within the plugin and I think it would be nice not having them setup a lot of data in two separate places.


Solution

  • You can use reflection regardless of MEF to get the attribute value:

    [ExportMetadata("guid", "0db79a169xy741229a1b558a07867d60")]
    class PluginExport
    {
        void PrintGuid()
        {
            var guid = this.GetType()
                           .GetCustomAttributes(false)
                           .OfType<ExportMetadataAttribute>()
                           .Single(attribute => attribute.Name == "guid").Value;
    
            Console.WriteLine(guid); // Prints your value.
        }
    }