在介紹如何實作 Plugin 機制之前先介紹一下 Strategy Pattern,Strategy Pattern 為 Design Pattern 其中的一個 Pattern, 這個 Pattern 會透過一個 Interface 定義一系列的演算法,每一個演算法都有各自不同的實作方式,而這些演算法可以相互替換。因此 Plugin 機制會透過這個 Pattern 來實現。
系統架構總共分為三大專案
Main Program
IPlugin
lPlugin A, Plugin B ...
Plugin 和主程式皆不相互影響,各個 Plugin 使用各自參考的套件版本,但需要樣將參考的套件的DLL檔放到 Plugin 同一個目錄底下
Plugin 統一使用主系統使用的套件版本,Plugin 同一層目錄可以不用放參考套件的 DLL檔
Install-Package McMaster.NETCore.Plugins
using McMaster.NETCore.Plugins;
using System.Linq;
using System.Reflection;
public class MyPluginLoader
{
// pluginAssemblyPath: Plugin 的 DLL檔路徑
// pluginClassName: 要呼叫的 Plugin 的類別名稱 (包含 Namespace)
public IPlugin LoadPlugin(string pluginAssemblyPath, string pluginClassFullName)
{
// 透過 PluginLoader 讀取 DLL檔
var loader = PluginLoader.CreateFromAssemblyFile(assemblyFile: pluginAssemblyPath,
sharedTypes: new[] { typeof(IPlugin) });
// 取得實作 IPlugin 的類別 & 要呼叫的 Plugin 類別
Type type = loader.LoadDefaultAssembly()
.GetTypes()
.Where(t => typeof(IPlugin).IsAssignableFrom(t) &&
!t.IsAbstract &&
t.Name == pluginClassFullName)
.FirstOrDefault();
// 建立 Plugin Instance
var myPlugin = (IPlugin)Activator.CreateInstance(type);
return myPlugin
}
}
When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.
評論