gpt4 book ai didi

c# - PostBuild 事件中的 .NET Core Assembly.LoadFile

转载 作者:太空狗 更新时间:2023-10-29 17:53:11 26 4
gpt4 key购买 nike

我需要在构建后从我的一些 C# 类生成 typescript 文件。

我创建了 dotnet cli 工具 并添加了构建后事件

dotnet tsgenerator "$(TargetPath)"

其中 $(TargetPath) 是指向的宏,例如 D:\Test\bin\Release\netcoreapp2.0\my.dll

接下来,我尝试用下一种方式加载程序集:

public static void Main(string[] args)
{
var dllPath = args[0]; // "D:\Test\bin\Release\netcoreapp2.0\my.dll"
var assembly = Assembly.LoadFile(dllPath);
var types = assembly.GetExportedTypes(); // Throws exception
}

但是我得到了 ReflectionTypeLoadExceptionCould not load file or assembly for some references assemblies (for example, Microsoft.AspNetCore.Antiforgery) .

我如何为 .NET Core 应用程序加载程序集?

最佳答案

我在 github issue 找到了解决方案. amits1995留言和 angelcalvasp .

我已添加 <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>到我的 csproj 并使用此代码加载程序集:

public static class AssemblyLoader
{
public static Assembly LoadFromAssemblyPath(string assemblyFullPath)
{
var fileNameWithOutExtension = Path.GetFileNameWithoutExtension(assemblyFullPath);
var fileName = Path.GetFileName(assemblyFullPath);
var directory = Path.GetDirectoryName(assemblyFullPath);

var inCompileLibraries = DependencyContext.Default.CompileLibraries.Any(l => l.Name.Equals(fileNameWithOutExtension, StringComparison.OrdinalIgnoreCase));
var inRuntimeLibraries = DependencyContext.Default.RuntimeLibraries.Any(l => l.Name.Equals(fileNameWithOutExtension, StringComparison.OrdinalIgnoreCase));

var assembly = (inCompileLibraries || inRuntimeLibraries)
? Assembly.Load(new AssemblyName(fileNameWithOutExtension))
: AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyFullPath);

if (assembly != null)
LoadReferencedAssemblies(assembly, fileName, directory);

return assembly;
}

private static void LoadReferencedAssemblies(Assembly assembly, string fileName, string directory)
{
var filesInDirectory = Directory.GetFiles(directory).Where(x => x != fileName).Select(x => Path.GetFileNameWithoutExtension(x)).ToList();
var references = assembly.GetReferencedAssemblies();

foreach (var reference in references)
{
if (filesInDirectory.Contains(reference.Name))
{
var loadFileName = reference.Name + ".dll";
var path = Path.Combine(directory, loadFileName);
var loadedAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(path);
if (loadedAssembly != null)
LoadReferencedAssemblies(loadedAssembly, loadFileName, directory);
}
}
}
}

用法:

public static void Main(string[] args)
{
var dllPath = args[0]; // "D:\Test\bin\Release\netcoreapp2.0\my.dll"
var assembly = AssemblyLoader.LoadFromAssemblyPath(dllPath);
var types = assembly.GetExportedTypes(); // No exceptions
}

关于c# - PostBuild 事件中的 .NET Core Assembly.LoadFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51048970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com