【问题标题】:Mef import all types implementing an interface specified at runtimeMef 导入实现在运行时指定的接口的所有类型
【发布时间】:2025-12-11 21:05:01
【问题描述】:

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

示例用法:

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

这可能吗?

【问题讨论】:

    标签: c# .net c#-4.0 mef


    【解决方案1】:

    您可以使用 DirectoryCatalog 创建容器,然后调用 container.GetExportedValues&lt;IExcitingClass&gt;。这就是你想要的吗?

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        最近更新 更多