我正在嘗試為 ASP.NET Core 應用程式構建一個插件系統。我在應用程式中有一個名為“插件”的檔案夾。
一般來說,一個插件看起來像一個包含兩個檔案的檔案夾:Plugin.dll 和 Plugin.Views.dll 應用程式掃描這個檔案夾并加載這些程式集
foreach (var ext in extensionManager.Extensions)
{
mvcBuilder.AddApplicationPart(ext.Assembly);
if (ext.ViewsAssembly != null)
{
mvcBuilder.AddApplicationPart(ext.ViewsAssembly);
}
}
如果這些插件具有同名的 ViewComponents,我會收到錯誤訊息。Plugin1 中的模型可以傳遞到 Plugin2 的 Razor 視圖中。
The model item passed into the ViewDataDictionary is of type 'Plugin1.Models.MyModel',
but this ViewDataDictionary instance requires a model item of type 'Plugin2.Models.MyModel'
我該如何解決這個沖突?
uj5u.com熱心網友回復:
傳遞到 ViewDataDictionary 的模型項的型別為“Plugin1.Models.MyModel”,但此 ViewDataDictionary 實體需要型別為“Plugin2.Models.MyModel”的模型項
Plugin2.Models.MyModel如果此 ViewDataDictionary 實體需要型別為 的模型項,您可以嘗試使用全名Plugin2.Models.MyModel。這樣它就不會傳遞Plugin1.Models.MyModel給此 ViewDataDictionary。
uj5u.com熱心網友回復:
我通過將其添加Target到我的插件的 .csproj 檔案中解決了這個問題:
<Target Name="UpdateTargetPath" BeforeTargets="AssignRazorGenerateTargetPaths">
<ItemGroup>
<RazorGenerate Link="$(TargetName)\%(RazorGenerate.RelativeDir)%(RazorGenerate.FileName)%(RazorGenerate.Extension)" />
</ItemGroup>
</Target>
我以這個答案為基礎。我還Include從RazorGenerate標記中洗掉了該屬性,因為它RazorCompiledAttribute在生成的程式集中重復。
在主機應用程式方面,我擴展了視圖位置格式:
services.Configure<RazorViewEngineOptions>(opts =>
{
var pluginName = ext.Assembly.GetName().Name;
opts.ViewLocationFormats.Add($"/{pluginName}/Views/Shared/{{0}}.cshtml");
opts.ViewLocationFormats.Add($"/{pluginName}/{{1}}/Views/{{0}}.cshtml");
});
在插件中,我必須指定視圖的完全限定路徑:
return View($"/{this.GetType().Assembly.GetName().Name}/Views/Path/To/MyView.cshtml", model);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/356614.html
標籤:C# asp.net-mvc asp.net核心 插件
上一篇:ASP.Net6自定義WebApplicationFactory拋出例外
下一篇:在VisualStudio(ASP.NETCORE的本地除錯會話)中查詢ApplicationInsights時,如何確保沒有遙測資料丟失?
