繁体   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