首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

MEF 實戰(四):三大目錄類別與 AggregateCatalog 組合搜尋範圍

     編輯:關於C#

MEF 發現擴充組件的來源稱為 Catalog(目錄)。本文詳細說明三大內建目錄類別的使用時機與範例,並示範 AggregateCatalog 合併多個搜尋範圍,達成「外掛資料夾 + 專案內建擴充」並存。

三大 Catalog 比較

Catalog搜尋範圍典型用途
AssemblyCatalog指定組件當前專案、特定 DLL、單元測試組件
DirectoryCatalog資料夾(支援萬用字元)外掛資料夾、熱插拔目錄
ApplicationCatalog應用程式執行目錄ClickOnce、單檔部署、簡易自動發現

AssemblyCatalog:掃描當前組件

var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
var container = new CompositionContainer(catalog);
container.ComposeParts(this); // 匯入標記 [Import] 的屬性

DirectoryCatalog:掃描外掛資料夾

// 掃描 D:\Plugins 下所有 *.dll
var catalog = new DirectoryCatalog(@"D:\Plugins", "*.dll");
// 或只掃描 ext_ 開頭
var catalog = new DirectoryCatalog(@"D:\Plugins", "ext_*.dll");

WinForms 範例:使用者透過 FolderBrowserDialog 選擇資料夾 → DirectoryCatalog 發現擴充類別 → 顯示在 ComboBox → 選擇後呼叫 SaySomething()。

WinForms 介面佈局

外掛 DLL 放置資料夾

執行結果

AggregateCatalog:合併多個來源

情境:三個外掛在 D:\Plugins,第四個直接寫在主專案裡。用 AggregateCatalog 合併 DirectoryCatalog + AssemblyCatalog。

var aggregate = new AggregateCatalog();
aggregate.Catalogs.Add(new DirectoryCatalog(pluginPath));
aggregate.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly));

var container = new CompositionContainer(aggregate);
container.ComposeParts(this);

合併搜尋後發現第四個擴充

最佳實務建議

  • 生產環境:DirectoryCatalog 指定固定外掛資料夾,避免掃描整個安裝目錄影響啟動速度。
  • 開發/測試:AggregateCatalog 加入 AssemblyCatalog 方便除錯內建擴充。
  • 安全性:DirectoryCatalog 搭配強名稱/簽章驗證,防止惡意 DLL 被載入。
  • 效能:目錄建立較耗時,應在啟動階段一次性建立並快取 CompositionContainer。

掌握三大 Catalog 與 AggregateCatalog,就能靈活控制 MEF 的發現範圍——無論是熱插拔外掛、內建功能、或是單元測試替身,都能精準定位。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved