2011-01-14 80 views
0

我正在構建一個實現MEF的Windows服務的過程。這個想法是,該服務應該管理子組件並且是可插入的,其中可以在運行時引入任意數量的新組件,而不必經歷全面的服務重新編譯和部署場景。這些組件應該是可插拔的,這意味着只要我將一個輸出組件放到光盤上的指定文件夾中,Windows服務就應該說「嘿,這是一個運行的新組件」,並且只是做這件事。這是MEF的力量。非常酷的東西到目前爲止。Microsoft擴展性框架 - MEF CompositionContainer

我理解創建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()); 
      } 
     } 

任何反饋或輸入被讚賞。

謝謝, 邁克

回答

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

+0

謝謝,我可能要走這條路。這是另一件事,我沒有在上面簡單提及。對於CompositionContainer在每次定時查找期間發現的每個子組件,我將把子組件作業踢到一個單獨的線程中。爲了管理新線程的數量,我將不得不檢查是否有一個線程已經運行在上一次定時查找期間發現的子組件作業。你使用線程的經驗是多少,線程多少?在某些時候,我可能有15個以上的子組件用於這件事 – 2011-01-14 15:36:58

0

創建CompositionContainers應該便宜。創建目錄並不便宜,因爲必須檢查組件以查找MEF零件。所以如果可能的話,你應該在循環之外創建你的目錄。