我正在对 .NET Core 6 应用程序进行复杂的迁移,该应用程序具有一组共享程序集,由于我们的部署策略,这些程序集位于与主应用程序程序集不同的路径中。
库是静态链接的,因此我无法使用
AssemblyLoadContext
或 AppDomain
来扩展解析过程,遗憾的是。我看到 runtimeconfig.json
提供了添加 APP_PATHS
的可能性,这似乎有效,但我只设法使用绝对路径 - 这是无意义的,因为我不知道目标计算机上的实际路径。
我不能使用相对路径吗?每当我尝试甚至子路径时,我都会收到无法创建运行时的异常。这有什么神奇的语法吗?将程序集放在多个文件夹中不可能这么复杂......我觉得很愚蠢。
这里有人有想法吗?我不能仅仅改变部署结构/流程。
谢谢
我的评论的一个例子。我有三个项目:图书馆
A
、图书馆B
和应用程序C
。
A.csproj
和 B.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
ClassA
在项目中A
。
using System.Runtime.CompilerServices;
namespace A
{
public static class ClassA
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static int Plink()
{
return 1;
}
}
}
ClassB
using System.Runtime.CompilerServices;
namespace B
{
public class ClassB
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static int Plonk()
{
return 2;
}
}
}
C.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>exe</OutputType>
<TargetFrameworks>net8.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\A\A.csproj" Private="false" />
<ProjectReference Include="..\B\B.csproj" Private="false" />
</ItemGroup>
</Project>
Program.cs
using System.Runtime.CompilerServices;
using System.Runtime.Loader;
using A;
using B;
namespace C
{
public static class Program
{
public static void Main(string[] args)
{
SetupAssemblies();
Foo();
}
private static void SetupAssemblies()
{
AssemblyLoadContext.Default.Resolving += Default_Resolving;
}
private static System.Reflection.Assembly? Default_Resolving(AssemblyLoadContext arg1, System.Reflection.AssemblyName arg2)
{
Console.WriteLine($"Attempting to resolve {arg2}");
string assemblyPath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), $@"..\deps\{arg2.Name}.dll"));
return AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void Foo()
{
Console.WriteLine(ClassA.Plink() + ClassB.Plonk());
}
}
}
我的输出结构如下
~\Projects\SO\C\BIN\DEBUG
│
├───deps
│ A.dll
│ B.dll
└───net8.0
C.deps.json
C.dll
C.exe
C.pdb
C.runtimeconfig.json
程序输出:
尝试解析 A,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null
尝试解析 B,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null
3