c# - ASP.NET Core 中是否有 BuildManager.GetReferencedAssemblies() 的替代方法?
问题描述
在 ASP.NET MVC 5 中,我使用该BuildManager.GetReferencedAssemblies()
方法获取 bin 文件夹中的所有程序集并在依赖项启动之前加载它们,因此所有 dll 都可以被扫描和注入。
ASP.NET Core 中是否有替代方案?
我试过这段代码,但它开始给我加载错误,比如找不到文件异常。
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)
{
}
}
解决方案
我设法创建了一个解决方案,但我不确定它是否能解决所有情况。
我将发布为“在我的机器解决方案上工作”
主要区别在于从 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)
{
}
}
推荐阅读
- ios - 当用户从 iPhone 的控制中心使用屏幕录制工具时,如何暂停特定屏幕的屏幕录制
- regex - Perl 中的 qr/ 和 m/ 有什么区别?
- java - 为什么要明确定义 KafkaTemplate bean?
- python-3.x - 升级到 Python 3.8.5 后所有模块都不可用
- javascript - 如何在各种屏幕尺寸上保持绝对 Touchables 一致?
- node.js - 使用 mineflayer 进行节点 JS 的 Minecraft 机器人错误
- javascript - CSS 网格不工作。当我在 Chrome 中检查时,代码都没有显示
- r - 将记录移动到R中的不同列和行
- laravel - Laravel Eloquent WhereHas 查询联合后
- c++ - C++ 中的当前 UTC 时间点