Mef import all types implementing an interface specified at runtime
Can i write a class to use mef to import all types implementing a specific interface and then specify this interface at run time. (i know i need to tag the implementors 开发者_JAVA技巧with export)
Example usage:
IEnumerable<IExcitingClass> excitingClasses = ClassImporter<IExcitingInterface>.ImportAllFrom(specifyDirectory);
Is this possible?
You can create a container using a DirectoryCatalog, and call container.GetExportedValues<IExcitingClass>
. Is that what you want?
At run time you could only use string to specify your interface.
public IEnumerable<object> GetAllInheritors(string interfaceName)
{
Assembly assembly = this.GetType().Assembly;
foreach (var part in Container.Catalog.Parts)
{
Type type = assembly.GetType(part.ToString());
if (type != null)
if (type.GetInterface(interfaceName) != null)
{
yield return part.CreatePart().GetExportedValue(part.ExportDefinitions.First());
}
}
}
精彩评论