2011-02-24 65 views
3

我可以编写一个类以使用mef导入实现特定接口的所有类型,然后在运行时指定此接口。 (我知道我需要标记与出口实施者)Mef导入实现在运行时指定的接口的所有类型

用法示例:

IEnumerable<IExcitingClass> excitingClasses = ClassImporter<IExcitingInterface>.ImportAllFrom(specifyDirectory); 

这可能吗?

回答

1

您可以使用DirectoryCatalog创建容器,并致电container.GetExportedValues<IExcitingClass>。那是你要的吗?

+0

这就是我失踪的欢呼! – GreyCloud 2011-02-25 15:31:31

1

在运行时你只能使用字符串来指定你的接口。

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()); 
       } 
     } 
    }