簡體   English   中英

加載 ASP.NET Core MVC 5 項目的程序集時出現 FileNotFoundException

[英]FileNotFoundException when loading assembly of ASP.NET Core MVC 5 project

我正在嘗試探索屬於 ASP.NET Core MVC 項目的程序集。 該項目是用 .NET 5 制作的。

問題是,當我嘗試探索程序集的類型時,它會引發FileNotFoundException並顯示以下消息: Could not load file or assembly 'Microsoft.AspNetCore.Mvc.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. El sistema no puede encontrar el archivo especificado Could not load file or assembly 'Microsoft.AspNetCore.Mvc.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. El sistema no puede encontrar el archivo especificado

發出dotnet build命令可以毫無問題地編譯項目。

Exploring the corresponding.csproj file, I found that the Microsoft.AspNetCore.Mvc.Core dependency is not declared in the project file, but the SDK indicated in the project file's XML root is Microsoft.NET.Sdk.Web , and I understand that將該項目標記為 ASP.NET 核心項目,但我找不到一種方法來引入必要的依賴項來加載程序集。

代碼如下。

加載程序集的代碼:

var reader_context = new ReaderLoadContext(artifact_dir);
var assembly_path = ""; //Path of the compiled assembly
var assembly = reader_context.LoadFromAssemblyPath(assembly_path);
//Here's where it crashes
var target_types = assembly.ExportedTypes.Where(t => t.BaseType != null && t.BaseType.Name == "ControllerBase").ToArray();

ReaderLoadContext的代碼:

public class ReaderLoadContext : AssemblyLoadContext
{
    private AssemblyDependencyResolver _resolver;

    public ReaderLoadContext(string readerLocation)
    {
        _resolver = new AssemblyDependencyResolver(readerLocation);
    }

    protected override Assembly Load(AssemblyName assemblyName)
    {
        var assembly_path = _resolver.ResolveAssemblyToPath(assemblyName);
        if (assembly_path != null)
        {
            return LoadFromAssemblyPath(assembly_path);
        }

        return null;
    }

    protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
    {
        var library_path = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
        if (library_path != null)
        {
            return LoadUnmanagedDllFromPath(library_path);
        }
        return IntPtr.Zero;
    }
}

事實證明, 這是 AssemblyLoadContext 的一個已知限制,其中一種解決方案(更像是一種丑陋的解決方法)是在探索所需程序集的應用程序中添加對缺失框架的引用。 我在我的應用程序的.csproj 文件中添加了一個PackageReference項,現在它正確加載了我要掃描的程序集。

我不知道我是否應該將此標記為答案。 一方面,它可以滿足我的需要。 OTOH,它強制開發人員事先添加所有可能的框架引用以防萬一,如果微軟(或第三方)發布另一個框架,它需要發布應用程序的新版本。

所以希望有人知道一個更優雅的解決方案。

感謝@deepak-msft 和其他所有人的幫助。

暫無
暫無

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

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