首页 > 解决方案 > ASP.NET Core 中是否有 BuildManager.GetReferencedAssemblies() 的替代方法?

问题描述

在 ASP.NET MVC 5 中,我使用该BuildManager.GetReferencedAssemblies()方法获取 bin 文件夹中的所有程序集并在依赖项启动之前加载它们,因此所有 dll 都可以被扫描和注入。

ASP.NET Core 中是否有替代方案?

https://docs.microsoft.com/en-us/dotnet/api/system.web.compilation.buildmanager.getreferencedassemblies?view=netframework-4.7.2

我试过这段代码,但它开始给我加载错误,比如找不到文件异常。

foreach (var compilationLibrary in deps.CompileLibraries)
{
    foreach (var resolveReferencePath in compilationLibrary.ResolveReferencePaths())
    {
        Console.WriteLine($"\t\tReference path: {resolveReferencePath}");
        dlls.Add(resolveReferencePath);
    }
}
dlls = dlls.Distinct().ToList();
var infolder = dlls.Where(x => x.Contains(Directory.GetCurrentDirectory())).ToList();
foreach (var item in infolder)
{
    try
    {
        Assembly.LoadFile(item);
    }
    catch (System.IO.FileLoadException loadEx)
    {

    } // The Assembly has already been loaded.
    catch (BadImageFormatException imgEx)
    {

    } // If a BadImageFormatException exception is thrown, the file is not an assembly.
    catch (Exception ex)
    {

    }
}

标签: c#asp.net-core

解决方案


我设法创建了一个解决方案,但我不确定它是否能解决所有情况。

我将发布为“在我的机器解决方案上工作”

主要区别在于从 Assembly.LoadFile 更改为 AssemblyLoadContext.Default.LoadFromAssemblyPath

我用这篇文章作为研究

https://natemcmaster.com/blog/2018/07/25/netcore-plugins/ https://github.com/dotnet/coreclr/blob/v2.1.0/Documentation/design-docs/assemblyloadcontext.md

        var dlls = DependencyContext.Default.CompileLibraries
            .SelectMany(x => x.ResolveReferencePaths())
            .Distinct()
            .Where(x => x.Contains(Directory.GetCurrentDirectory()))
            .ToList();
        foreach (var item in dlls)
        {
            try
            {
                AssemblyLoadContext.Default.LoadFromAssemblyPath(item);
            }
            catch (System.IO.FileLoadException loadEx)
            {
            } // The Assembly has already been loaded.
            catch (BadImageFormatException imgEx)
            {
            } // If a BadImageFormatException exception is thrown, the file is not an assembly.
            catch (Exception ex)
            {
            }
        }

推荐阅读