先簡單介紹下項目(由於重新基於模塊化設計了整個項目,所以目前整個項目功能不多)
1.Asp.Net Core 3.1.2+MSSQL2019(LINUX版)
2.中間件涉及Redis、RabbitMQ等
3.完全模塊化的設計,支持每個模塊有獨立的靜態資源文件
github開源地址:
https://github.com/yupingyong/mango
上一張項目結構圖:
上圖中 Modules目錄下放的項目的模塊
Mango.WebHost 承載整個項目運行
Mango.Framework 封裝整個項目模塊化核心
下面我會分享實現模塊化的幾個核心要點,更詳細的我會在後續的博文中陸續發佈.
框架如何去加載所寫的模塊這是最核心的問題之一,好在Asp.Net Core MVC爲模塊化提供了一個部件管理類
Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager
它支持從外部DLL程序集加載組件以及組件的管理.不過要從外部組件去獲取哪些是組件我們需要藉助一個工廠類ApplicationPartFactory,這個類支持從外部程序集得到對應的控制器信息,核心代碼如下:
/// <summary>
/// 向MVC模塊添加外部應用模塊組件
/// </summary>
/// <param name="mvcBuilder"></param>
/// <param name="assembly"></param>
private static void AddApplicationPart(IMvcBuilder mvcBuilder, Assembly assembly)
{
var partFactory = ApplicationPartFactory.GetApplicationPartFactory(assembly);
foreach (var part in partFactory.GetApplicationParts(assembly))
{
mvcBuilder.PartManager.ApplicationParts.Add(part);
}
var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: false);
foreach (var relatedAssembly in relatedAssemblies)
{
partFactory = ApplicationPartFactory.GetApplicationPartFactory(relatedAssembly);
foreach (var part in partFactory.GetApplicationParts(relatedAssembly))
{
mvcBuilder.PartManager.ApplicationParts.Add(part);
mvcBuilder.PartManager.ApplicationParts.Add(new CompiledRazorAssemblyPart(relatedAssembly));
}
}
}
上面的代碼展示瞭如何加載控制器信息,但是視圖文件在項目生成的時候是單獨的*.Views.dll文件,我們接下來介紹如何加載視圖文件,同樣還是用到了ApplicationPartManager類
mvcBuilder.PartManager.ApplicationParts.Add(new CompiledRazorAssemblyPart(module.ViewsAssembly));
new一個CompiledRazorAssemblyPart對象表示添加進去的是視圖編譯文件,完整的核心代碼
/// <summary>
/// 添加MVC組件
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection AddCustomizedMvc(this IServiceCollection services)
{
services.AddSession();
var mvcBuilder = services.AddControllersWithViews(options=> {
//添加訪問授權過濾器
options.Filters.Add(new AuthorizationComponentFilter());
})
.AddJsonOptions(options=> {
options.JsonSerializerOptions.Converters.Add(new DateTimeToStringConverter());
});
foreach (var module in GlobalConfiguration.Modules)
{
if (module.IsApplicationPart)
{
if (module.Assembly != null)
AddApplicationPart(mvcBuilder, module.Assembly);
if (module.ViewsAssembly != null)
mvcBuilder.PartManager.ApplicationParts.Add(new CompiledRazorAssemblyPart(module.ViewsAssembly));
}
}
return services;
}
那如何去加載程序集呢?這裏我使用了自定義的ModuleAssemblyLoadContext去加載程序集,這個類繼承自AssemblyLoadContext(它支持卸載加載過的程序集,但是部件添加到MVC中時,好像不支持動態卸載會出現異常,可能是我還沒研究透吧)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Loader;
namespace Mango.Framework.Module
{
public class ModuleAssemblyLoadContext : AssemblyLoadContext
{
public ModuleAssemblyLoadContext() : base(true)
{
}
}
}
在使用ModuleAssemblyLoadContext類加載程序集時,先使用FileStream把程序集文件讀取出來(這樣能夠避免文件一直被佔用,方便開發中編譯模塊時報文件被佔用的異常),加載文件路徑時需要注意的問題一定要使用/(\在windows server下沒問題,但是如果在linux下部署就會出現問題),代碼如下:
/// <summary>
/// 添加模塊
/// </summary>
/// <param name="services"></param>
/// <param name="contentRootPath"></param>
/// <returns></returns>
public static IServiceCollection AddModules(this IServiceCollection services, string contentRootPath)
{
try
{
GlobalConfiguration.Modules = _moduleConfigurationManager.GetModules();
ModuleAssemblyLoadContext context = new ModuleAssemblyLoadContext();
foreach (var module in GlobalConfiguration.Modules)
{
var dllFilePath = Path.Combine(contentRootPath, $@"Modules/{module.Id}/{module.Id}.dll");
var moduleFolder = new DirectoryInfo(dllFilePath);
if (File.Exists(moduleFolder.FullName))
{
using FileStream fs = new FileStream(moduleFolder.FullName, FileMode.Open);
module.Assembly = context.LoadFromStream(fs);
//
RegisterModuleInitializerServices(module, ref services);
}
else
{
_logger.Warn($"{dllFilePath} file is not find!");
}
//處理視圖文件程序集加載
var viewsFilePath = Path.Combine(contentRootPath, $@"Modules/{module.Id}/{module.Id}.Views.dll");
moduleFolder = new DirectoryInfo(viewsFilePath);
if (File.Exists(moduleFolder.FullName))
{
using FileStream viewsFileStream = new FileStream(moduleFolder.FullName, FileMode.Open);
module.ViewsAssembly = context.LoadFromStream(viewsFileStream);
}
else
{
_logger.Warn($"{viewsFilePath} file is not find!");
}
}
}
catch (Exception ex)
{
_logger.Error(ex);
}
return services;
}
上面簡單介紹瞭如何利用MVC自帶的部件管理類去加載外部程序集,這裏需要說明的一點的是每個模塊我們採用創建區域的方式去區分模塊,如下圖展示的賬號模塊結構
基於模塊化開發我們可能碰到一個比較常見的需求就是,如果每個模塊需要擁有自己獨立的靜態資源文件呢?這種情況如何去解決呢?
好在MVC框架也提供了一個靜態資源配置方法UseStaticFiles,我們在Configure方法中啓用靜態資源組件時,可以自定義設置靜態文件訪問的路徑,設置代碼如下
//設置每個模塊約定的靜態文件目錄
foreach (var module in GlobalConfiguration.Modules)
{
if (module.IsApplicationPart)
{
var modulePath = $"{env.ContentRootPath}/Modules/{module.Id}/wwwroot";
if (Directory.Exists(modulePath))
{
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(modulePath),
RequestPath = new PathString($"/{module.Name}")
});
}
}
}
上述代碼片段中我們能夠看到通過new StaticFileOptions()添加配置項, StaticFileOptions中有兩個重要的屬性,只需要配置好這兩個就能滿足基本需求了
FileProvider:該屬性表示文件的實際所在目錄(如:{env.ContentRootPath}/Modules/Mango.Module.Account/wwwroot)
RequestPath:該屬性表示文件的請求路徑(如 /account/test.js 這樣訪問到就是 {env.ContentRootPath}/Modules/Mango.Module.Account/wwwroot下的test.js文件)
這篇博文我就暫時只做一個模塊化開發實現的核心代碼展示和說明,更具體的只能在接下來的博文中展示了.
其實我也開發了一個前後分離的,只剩下鑑權,實現的核心和上面所寫的一樣,這裏我就只把開源地址分享出來,我後面還是會用業餘時間來繼續完成它
https://github.com/yupingyong/mango-open
該項目我已經在linux 上使用docker容器部署了,具體地址我就不發佈了(避免打廣告的嫌疑,我截幾張效果圖)
結語:這個項目我會一個更新下去,接下去這個框架會向DDD發展.
因爲喜歡.net 技術棧,所以願意在開發社區分享我的知識成果,也想向社區的人學習更好的編碼風格,更高一層編程技術.