從零開始實現ASP.NET Core MVC的插件式開發(六) – 如何載入插件引用
- 2019 年 10 月 22 日
- 筆記
標題:從零開始實現ASP.NET Core MVC的插件式開發(六) – 如何載入插件引用。
作者:Lamond Lu
地址:https://www.cnblogs.com/lwqlun/p/11717254.html
源程式碼:https://github.com/lamondlu/DynamicPlugins
前景回顧
- 從零開始實現ASP.NET Core MVC的插件式開發(一) – 使用Application Part動態載入控制器和視圖
- 從零開始實現ASP.NET Core MVC的插件式開發(二) – 如何創建項目模板
- 從零開始實現ASP.NET Core MVC的插件式開發(三) – 如何在運行時啟用組件
- 從零開始實現ASP.NET Core MVC的插件式開發(四) – 插件安裝
- 從零開始實現ASP.NET Core MVC的插件式開發(五) – 使用AssemblyLoadContext實現插件的升級和刪除
簡介
在前一篇中,我給大家演示了如何使用.NET Core 3.0中新引入的AssemblyLoadContext
來實現運行時升級和刪除插件。完成此篇之後,我得到了很多園友的回饋,很高興有這麼多人能夠參與進來,我會根據大家的回饋,來完善這個項目。本篇呢,我將主要解決載入插件引用的問題,這個也是回饋中被問的最多的問題。
問題用例
在之前做的插件中,我們做的都是非常非常簡單的功能,沒有引入任何的第三方庫。但是正常情況下,我們所創建的插件或多或少的都會引用一些第三方庫,那麼下面我們來嘗試一下,使用我們先前的項目,載入一個使用第三方程式集, 看看會的得到什麼結果。
這裡為了模擬,我創建了一個新的類庫項目DemoReferenceLibrary
, 並在之前的DemoPlugin1
項目中引用DemoReferenceLibrary
項目。
在DemoReferenceLibrary
中,我新建了一個類Demo.cs文件, 其程式碼如下:
public class Demo { public string SayHello() { return "Hello World. Version 1"; } }
這裡就是簡單的通過SayHello
方法,返回了一個字元串。
然後在DemoPlugin1
項目中,我們修改之前創建的Plugin1Controller
,從Demo
類中通過SayHello
方法得到需要在頁面中顯示的字元串。
[Area("DemoPlugin1")] public class Plugin1Controller : Controller { public IActionResult HelloWorld() { var content = new Demo().SayHello(); ViewBag.Content = content; return View(); } }
最後我們打包一下插件,重新將其安裝到系統中,訪問插件路由之後,就會得到以下錯誤。
這裡就是大部分同學遇到的問題,無法載入程式集DemoReferenceLibrary
。
如何載入插件引用?
這個問題的原因很簡單,就是當通過AssemblyLoadContext
載入程式集的時候,我們只載入了插件程式集,沒有載入它引用的程式集。
例如,我們以DemoPlugin1
的為例,在這個插件的目錄如下
在這個目錄中,除了我們熟知的DemoPlugin1.dll
,DemoPlugin1.Views.dll
之外,還有一個DemoReferenceLibrary.dll
文件。 這個文件我們並沒有在插件啟用時載入到當前的AssemblyLoadContext
中,所以在訪問插件路由時,系統找不到這個組件的dll文件。
為什麼Mystique.Core.dll
、System.Data.SqlClient.dll
、Newtonsoft.Json.dll
這些DLL不會出現問題呢?
在.NET Core中有2種LoadContext
。 一種是我們之前介紹的AssemblyLoadContext
, 它是一種自定義LoadContext
。 另外一種就是系統默認的DefaultLoadContext
。當一個.NET Core應用啟動的時候,都會創建並引用一個DefaultLoadContext
。
如果沒有指定LoadContext
, 系統默認會將程式集都載入到DefaultLoadContext
中。這裡我們可以查看一下我們的主站點項目,這個項目我們也引用了Mystique.Core.dll
、System.Data.SqlClient.dll
、Newtonsoft.Json.dll
。
在.NET Core的設計文檔中,對於程式集載入有這樣一段描述
If the assembly was already present in A1’s context, either because we had successfully loaded it earlier, or because we failed to load it for some reason, we return the corresponding status (and assembly reference for the success case).
However, if C1 was not found in A1’s context, the Load method override in A1’s context is invoked.
- For Custom LoadContext, this override is an opportunity to load an assembly before the fallback (see below) to Default LoadContext is attempted to resolve the load.
- For Default LoadContext, this override always returns null since Default Context cannot override itself.
這裡簡單來說,意思就是當在一個自定義LoadContext
中載入程式集的時候,如果找不到這個程式集,程式會自動去默認LoadContext
中查找,如果默認LoadContext
中都找不到,就會返回null
。
由此,我們之前的疑問就解決了,這裡正是因為主站點已經載入了所需的程式集,雖然在插件的AssemblyLoadContext
中找不到這個程式集,程式依然可以通過默認LoadContext
來載入程式集。
那麼是不是真的就沒有問題了呢?
其實我不是很推薦用以上的方式來載入第三方程式集。主要原因有兩點
- 不同插件可以引用不同版本的第三方程式集,可能不同版本的第三方程式集實現不同。 而默認
LoadContext
只能載入一個版本,導致總有一個插件引用該程式集的功能失效。 - 默認
LoadContext
中可能載入的第三方程式集與其他插件都不同,導致其他插件功能引用該程式集的功能失效。
所以這裡最正確的方式,還是放棄使用默認LoadContext
載入程式集,保證每個插件的AssemblyLoadContext
都完全載入所需的程式集。
那麼如何載入這些第三方程式集呢?我們下面就來介紹兩種方式
- 原始方式
- 使用插件快取
原始方式
原始方式比較暴力,我們可以選擇載入插件程式集的同時,載入程式集所在目錄中所有的dll文件。
這裡首先我們創建了一個插件引用庫載入器介面IReferenceLoader
。
public interface IRefenerceLoader { public void LoadStreamsIntoContext(CollectibleAssemblyLoadContext context, string folderName, string excludeFile); }
然後我們創建一個默認的插件引用庫載入器DefaultReferenceLoader
,其程式碼如下:
public class DefaultReferenceLoader : IRefenerceLoader { public void LoadStreamsIntoContext(CollectibleAssemblyLoadContext context, string folderName, string excludeFile) { var streams = new List<Stream>(); var di = new DirectoryInfo(folderName); var allReferences = di.GetFiles("*.dll").Where(p => p.Name != excludeFile); foreach (var file in allReferences) { using (var sr = new StreamReader(file.OpenRead())) { context.LoadFromStream(sr.BaseStream); } } } }
程式碼解釋
- 這裡我是為了排除當前已經載入插件程式集,所以添加了一個
excludeFile
參數。 folderName
即當前插件的所在目錄,這裡我們通過DirectoryInfo
類的GetFiles
方法,獲取了當前指定folderName
目錄中的所有dll文件。- 這裡我依然通過文件流的方式載入了插件所需的第三方程式集。
完成以上程式碼之後,我們還需要修改啟用插件的兩部分程式碼
- [MystiqueStartup.cs] – 程式啟動時,注入
IReferenceLoader
服務,啟用插件 - [MvcModuleSetup.cs] – 在插件管理頁面,觸發啟用插件操作
MystiqueStartup.cs
public static void MystiqueSetup(this IServiceCollection services, IConfiguration configuration) { ... services.AddSingleton<IReferenceLoader, DefaultReferenceLoader>(); var mvcBuilder = services.AddMvc(); var provider = services.BuildServiceProvider(); using (var scope = provider.CreateScope()) { ... foreach (var plugin in allEnabledPlugins) { var context = new CollectibleAssemblyLoadContext(); var moduleName = plugin.Name; var filePath = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\{moduleName}\{moduleName}.dll"; var referenceFolderPath = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\{moduleName}"; _presets.Add(filePath); using (var fs = new FileStream(filePath, FileMode.Open)) { var assembly = context.LoadFromStream(fs); loader.LoadStreamsIntoContext(context, referenceFolderPath, $"{moduleName}.dll"); ... } } } ... }
MvcModuleSetup.cs
public void EnableModule(string moduleName) { if (!PluginsLoadContexts.Any(moduleName)) { var context = new CollectibleAssemblyLoadContext(); var filePath = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\{moduleName}\{moduleName}.dll"; var referenceFolderPath = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\{moduleName}"; using (var fs = new FileStream(filePath, FileMode.Open)) { var assembly = context.LoadFromStream(fs); _referenceLoader.LoadStreamsIntoContext(context, referenceFolderPath, $"{moduleName}.dll"); ... } } else { var context = PluginsLoadContexts.GetContext(moduleName); var controllerAssemblyPart = new MystiqueAssemblyPart(context.Assemblies.First()); _partManager.ApplicationParts.Add(controllerAssemblyPart); } ResetControllActions(); }
現在我們重新運行之前的項目,並訪問插件1的路由,你會發現頁面正常顯示了,並且頁面內容也是從DemoReferenceLibrary
程式集中載入出來了。
使用插件快取
原始方式雖然可以幫助我們成功載入插件引用程式集,但是它並不效率,如果插件1和插件2引用了相同的程式集,當插件1的AssemblyLoadContext
載入所有的引用程式集之後,插件2會將插件1所乾的事情重複一遍。這並不是我們想要的,我們希望如果多個插件同時使用了相同的程式集,就不需要重複讀取dll文件了。
如何避免重複讀取dll文件呢?這裡我們可以使用一個靜態字典來快取文件流資訊,從而避免重複讀取dll文件。
如果大家覺著在ASP.NET Core MVC中使用靜態字典來快取文件流資訊不安全,可以改用其他快取方式,這裡只是為了簡單演示。
這裡我們首先創建一個引用程式集快取容器介面IReferenceContainer
, 其程式碼如下:
public interface IReferenceContainer { List<CachedReferenceItemKey> GetAll(); bool Exist(string name, string version); void SaveStream(string name, string version, Stream stream); Stream GetStream(string name, string version); }
程式碼解釋
GetAll
方法會在後續使用,用來獲取系統中載入的所有引用程式集Exist
方法判斷了指定版本程式集的文件流是否存在SaveStream
是將指定版本的程式集文件流保存到靜態字典中GetStream
是從靜態字典中拉取指定版本程式集的文件流
然後我們可以創建一個引用程式集快取容器的默認實現DefaultReferenceContainer
類,其程式碼如下:
public class DefaultReferenceContainer : IReferenceContainer { private static Dictionary<CachedReferenceItemKey, Stream> _cachedReferences = new Dictionary<CachedReferenceItemKey, Stream>(); public List<CachedReferenceItemKey> GetAll() { return _cachedReferences.Keys.ToList(); } public bool Exist(string name, string version) { return _cachedReferences.Keys.Any(p => p.ReferenceName == name && p.Version == version); } public void SaveStream(string name, string version, Stream stream) { if (Exist(name, version)) { return; } _cachedReferences.Add(new CachedReferenceItemKey { ReferenceName = name, Version = version }, stream); } public Stream GetStream(string name, string version) { var key = _cachedReferences.Keys.FirstOrDefault(p => p.ReferenceName == name && p.Version == version); if (key != null) { _cachedReferences[key].Position = 0; return _cachedReferences[key]; } return null; } }
這個類比較簡單,我就不做太多解釋了。
完成了引用快取容器之後,我修改了之前創建的IReferenceLoader
介面,及其默認實現DefaultReferenceLoader
。
public interface IReferenceLoader { public void LoadStreamsIntoContext(CollectibleAssemblyLoadContext context, string moduleFolder, Assembly assembly); }
public class DefaultReferenceLoader : IReferenceLoader { private IReferenceContainer _referenceContainer = null; private readonly ILogger<DefaultReferenceLoader> _logger = null; public DefaultReferenceLoader(IReferenceContainer referenceContainer, ILogger<DefaultReferenceLoader> logger) { _referenceContainer = referenceContainer; _logger = logger; } public void LoadStreamsIntoContext(CollectibleAssemblyLoadContext context, string moduleFolder, Assembly assembly) { var references = assembly.GetReferencedAssemblies(); foreach (var item in references) { var name = item.Name; var version = item.Version.ToString(); var stream = _referenceContainer.GetStream(name, version); if (stream != null) { _logger.LogDebug($"Found the cached reference '{name}' v.{version}"); context.LoadFromStream(stream); } else { if (IsSharedFreamwork(name)) { continue; } var dllName = $"{name}.dll"; var filePath = $"{moduleFolder}\{dllName}"; if (!File.Exists(filePath)) { _logger.LogWarning($"The package '{dllName}' is missing."); continue; } using (var fs = new FileStream(filePath, FileMode.Open)) { var referenceAssembly = context.LoadFromStream(fs); var memoryStream = new MemoryStream(); fs.Position = 0; fs.CopyTo(memoryStream); fs.Position = 0; memoryStream.Position = 0; _referenceContainer.SaveStream(name, version, memoryStream); LoadStreamsIntoContext(context, moduleFolder, referenceAssembly); } } } } private bool IsSharedFreamwork(string name) { return SharedFrameworkConst.SharedFrameworkDLLs.Contains($"{name}.dll"); } }
程式碼解釋:
- 這裡
LoadStreamsIntoContext
方法的assembly
參數,即當前插件程式集。 - 這裡我通過
GetReferencedAssemblies
方法,獲取了插件程式集引用的所有程式集。 - 如果引用程式集在引用容器中不存在,我們就是用文件流載入它,並將其保存到引用容器中, 如果引用程式集已存在於引用容器,就直接載入到當前插件的
AssemblyLoadContext
中。這裡為了檢驗效果,如果程式集來自快取,我使用日誌組件輸出了一條日誌。 - 由於插件引用的程式集,有可能是來自
Shared Framework
, 這種程式集是不需要載入的,所以這裡我選擇跳過這類程式集的載入。(這裡我還沒有考慮Self-Contained發布的情況,後續這裡可能會更改)
最後我們還是需要修改MystiqueStartup.cs
和MvcModuleSetup.cs
中啟用插件的程式碼。
MystiqueStartup.cs
public static void MystiqueSetup(this IServiceCollection services, IConfiguration configuration) { ... services.AddSingleton<IReferenceContainer, DefaultReferenceContainer>(); services.AddSingleton<IReferenceLoader, DefaultReferenceLoader>(); ... var mvcBuilder = services.AddMvc(); var provider = services.BuildServiceProvider(); using (var scope = provider.CreateScope()) { ... foreach (var plugin in allEnabledPlugins) { ... using (var fs = new FileStream(filePath, FileMode.Open)) { var assembly = context.LoadFromStream(fs); loader.LoadStreamsIntoContext(context, referenceFolderPath, assembly); ... } } } ... }
MvcModuleSetup.cs
public void EnableModule(string moduleName) { if (!PluginsLoadContexts.Any(moduleName)) { ... using (var fs = new FileStream(filePath, FileMode.Open)) { var assembly = context.LoadFromStream(fs); _referenceLoader.LoadStreamsIntoContext(context, referenceFolderPath, assembly); ... } } else { ... } ResetControllActions(); }
完成程式碼之後,為了檢驗效果,我創建了另外一個插件DemoPlugin2
, 這個項目的程式碼和DemoPlugin1
基本一樣。程式啟動時,你會發現DemoPlugin2
所使用的引用程式集都是從快取中載入的,而且DemoPlugin2
的路由也能正常訪問。
添加頁面來顯示載入的第三方程式集
這裡為了顯示一下系統中載入了哪些程式集,我添加了一個新頁面Assembilies
, 這個頁面就是調用了IReferenceContainer
介面中定義的GetAll
方法,顯示了靜態字典中,所有載入的程式集。
效果如下:
幾個測試場景
最後,在編寫完成以上程式碼功能之後,我們使用以下幾種場景來測試一下,看一看AssemblyLoadContext
為我們提供的強大功能。
場景1
2個插件,一個引用DemoReferenceLibrary
的1.0.0.0版本,另外一個引用DemoReferenceLibrary
的1.0.1.0版本。其中1.0.0.0版本,SayHello
方法返回的字元串是"Hello World. Version 1", 1.0.1.0版本, SayHello
方法返回的字元串是「Hello World. Version 2」。
啟動項目,安裝插件1和插件2,分別運行插件1和插件2的路由,你會得到不同的結果。這說明AssemblyLoadContext
為我們做了很好的隔離,插件1和插件2雖然引用了相同插件的不同版本,但是互相之間完全沒有影響。
場景2
當2個插件使用了相同的第三方庫,並載入完成之後,禁用插件1。雖然他們引用的程式集相同,但是你會發現插件2還是能夠正常訪問,這說明插件1的AssemblyLoadContext
的釋放,對插件2的AssemblyLoadContext
完全沒有影響。
總結
本篇我為大家介紹了如何解決插件引用程式集的載入問題,這裡我們講解了兩種方式,原始方式和快取方式。這兩種方式的最終效果雖然相同,但是快取方式的效率明顯更高。後續我會根據回饋,繼續添加新內容,大家敬請期待。