MEF and exporting based on Metadata
In your example, you're using GetExports<T>
, instead of GetExports<T,TMetadata>
. In a simple example, you can use GetExports<IController, IDictionary<string, object>>
, which would allow you to query, but a nicer way of doing it is to create a custom metadata contract:
public interface INameMetadata
{
string Name { get; }
}
Which you can then use as:
[Export(typeof(IController))]
[ExportMetadata("Name", "Home")]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class HomeController : Controller { }
And then change your import to:
var controller = _container.GetExports<IController, INameMetadata>()
.Where(e => e.Metadata.Name.Equals(controllerName))
.Select(e => e.Value)
.FirstOrDefault();
Going one step further, you could combine your Export
and ExportMetadata
attributes into a single attribute:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false), MetadataAttribute]
public class ExportControllerAttribute : ExportAttribute, INameMetadata
{
public ExportControllerAttribute(string name)
: base(typeof(IController))
{
Name = name;
}
public string Name { get; private set; }
}
Now, you can use that with your export:
[ExportController("Home"), PartCreationPolicy(CreationPolicy.NonShared)]
public class HomeController : Controller { }