在 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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
我设法创建一个解决方案,但我不确定它能解决所有情况。
我将发布为“适用于我的机器解决方案”
主要区别是从 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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1882 次 |
| 最近记录: |