簡體   English   中英

ASP.NET MVC - 從外部動態加載視圖 DLL

[英]ASP.NET MVC - Dynamically load views from external DLL

我在我正在編寫的應用程序中有一個用例,其中我在動態加載的外部 DLL 中有邏輯。 現在我需要添加在駐留在外部 DLL 中的 ASP.NET MVC 視圖中顯示共享視圖的功能。

到目前為止我所做的是在我的ConfigureServices方法中添加以下內容:

UriBuilder uri = new UriBuilder(Assembly.GetEntryAssembly().CodeBase);
string fullPath = Uri.UnescapeDataString(uri.Path);
var mainDirectory = Path.GetDirectoryName(fullPath);
var assemblyFilePath = Path.Combine(mainDirectory, "MyLogic.dll");

var asmStream = File.OpenRead(assemblyFilePath);
var assembly = AssemblyLoadContext.Default.LoadFromStream(asmStream);

var part = new AssemblyPart(assembly);
services.AddControllersWithViews().ConfigureApplicationPartManager(apm => apm.ApplicationParts.Add(part));

只要將 DLL 添加為對項目的引用,這就可以正常工作。 如果我刪除引用,那么當我嘗試加載局部視圖時,我的應用程序會出現錯誤:

InvalidOperationException: The partial view 'MyView' was not found. The following locations were searched: /Views/Consent/MyView.cshtml /Views/Shared/MyView.cshtml

我嘗試做的是使用以下代碼列出應用程序的所有已知視圖:

var feature = new ViewsFeature();
applicationPartManager.PopulateFeature(feature);
var views = feature.ViewDescriptors.Select(x => x.RelativePath).ToList();

我看到的是,當我在項目中添加 DLL 作為參考時,我在列表中看到MyView.cshtml ,如果沒有,我就看不到它 - 上面的錯誤是有道理的。

但是我的用例表明未引用加載的 DLL。 當它不是參考時,有沒有辦法從中添加視圖?

謎團解決了......而不是ConfigureApplicationPartManager需要像這樣使用AddApplicationPart

UriBuilder uri = new UriBuilder(Assembly.GetEntryAssembly().CodeBase);
string fullPath = Uri.UnescapeDataString(uri.Path);
var mainDirectory = Path.GetDirectoryName(fullPath);
var assemblyFilePath = Path.Combine(mainDirectory, "Risco.Auth.Demo.Bridge.dll");

var asmStream = File.OpenRead(assemblyFilePath);
var assembly = AssemblyLoadContext.Default.LoadFromStream(asmStream);

services.AddControllersWithViews().AddApplicationPart(assembly);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM