【问题标题】:Microsoft Extensibility Framework - MEF CompositionContainerMicrosoft 可扩展性框架 - MEF CompositionContainer
【发布时间】:2011-01-14 15:25:11
【问题描述】:

我正在构建一个实现 MEF 的 Windows 服务。这个想法是服务应该管理子组件并且是可插拔的,其中可以在运行时引入任意数量的新组件,而无需经历完整的服务重新编译和部署场景。组件应该是可插入的,这意味着只要我将输出程序集放到磁盘上的指定文件夹中,Windows 服务就会说“嘿,这里有一个要运行的新组件……”然后就去做。这就是MEF的力量。到目前为止非常酷的东西。

我了解创建 AggregateCatalog 和 CompositionContainer 以导入所有可用子组件(组件)的概念。这一切都很好,并且在最初启动 Windows 服务时可以正常工作。但是,我最终将在运行时引入新组件,因此在某些时候我将需要 CompositionContainer 来识别添加的任何新输出程序集。

我对以下内容的担忧是对性能的任何影响。将 CompositionContainer 逻辑放入如下循环中是否安全/高效:

        [ImportMany(AllowRecomposition = true)]
        private IEnumerable<Lazy<IMySubComponentTask, IDictionary<string, object>>>                        
        MySubComponentTasks { get; set; }

        while (true)
        {
          //Create a general aggregate catalog
          var catalog = new AggregateCatalog();

          //Adds all the parts found in the same assembly as the Program class
          catalog.Catalogs.Add(new AssemblyCatalog(typeof(MySubComponentTaskFactory).Assembly));

          //Create a new directory catalog
          var directoryCatalog = new DirectoryCatalog(@".\Extensions");

          //Add the DLLs in the directory to the aggregate catalog
          catalog.Catalogs.Add(directoryCatalog);

          //Create the current composition container to create the parts
          var container = new CompositionContainer(catalog);

          //Fill the imports of this object
          try
          {
            container.ComposeParts(this);
          }
          catch (CompositionException compositionException)
          {
            Console.WriteLine(compositionException.ToString());
          }
       }

感谢任何反馈或意见。

谢谢, 迈克

【问题讨论】:

    标签: c# mef


    【解决方案1】:

    不,我不会将目录实例化放入循环中。但是,可能是 System.Timers.TimerSystem.Threading.Timer 定期检查插件目录 - 以最适合您的需要为准。

    由于您的 ImportMany 允许重新组合,您应该能够在运行时添加新组合:

    Timer checkPlugin = new Timer();
    
    //set CheckForPlugins as a timer callback or action
    void CheckForPlugins()
    {
        // add plugins catalog if found in directory
    }
    

    我发现了一些额外的信息:Recomposition and constructors

    【讨论】:

    • 谢谢,我可能会走这条路。这是另一件事,为简洁起见,我在上面没有提到。对于 CompositionContainer 在每次定时查找期间发现的每个子组件,我将把子组件作业踢到一个单独的线程中。为了管理新线程的数量,我将不得不检查是否有线程已经在运行在之前的定时查找期间发现的子组件作业。您使用线程的经验是什么?有多少线程太多了?在某个时候,我可能有 15 个以上的子组件用于这个东西
    • @michael:最大线程数取决于 CPU 和核心架构。我会参考任务并行库来管理组件线程。
    【解决方案2】:

    创建 CompositionContainer 应该很便宜。创建目录并不便宜,因为必须检查组件才能找到 MEF 零件。因此,如果可能,您应该在循环之外创建目录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      • 1970-01-01
      • 2010-10-28
      相关资源
      最近更新 更多