.NET Core 3.1控制台程序如何指定从子文件夹加载指定版本DLL?
解决.NET Core 3.1控制台程序加载指定子文件夹版本DLL的问题
方法1:通过runtimeconfig.json指定额外探测路径
如果你的程序没有runtimeconfig.json,直接在控制台程序根目录创建该文件,添加以下配置:
{ "runtimeOptions": { "additionalProbingPaths": [ "./你的子文件夹名称" ], "configProperties": { "System.Runtime.Loader.AssemblyLoadContext.Default": { "EnableRedirects": true } } } }
additionalProbingPaths用来指定运行时额外查找依赖的目录,填写你的子文件夹相对路径即可。- 同时要保证项目文件(.csproj)中引用的
dll1版本是6.x,和子文件夹里的DLL版本一致。
方法2:自定义AssemblyLoadContext手动加载目标DLL
在程序启动时,通过自定义加载上下文精准控制dll1的加载来源,绕开默认加载逻辑:
using System; using System.IO; using System.Reflection; using System.Runtime.Loader; class CustomDllLoadContext : AssemblyLoadContext { private readonly string _subFolderPath; public CustomDllLoadContext(string subFolderPath) => _subFolderPath = subFolderPath; protected override Assembly Load(AssemblyName assemblyName) { // 只处理dll1的加载逻辑 if (assemblyName.Name.Equals("dll1", StringComparison.OrdinalIgnoreCase)) { string dllFullPath = Path.Combine(_subFolderPath, $"{assemblyName.Name}.dll"); if (File.Exists(dllFullPath)) { return LoadFromAssemblyPath(dllFullPath); } } // 其他程序集用默认加载逻辑 return Default.LoadFromAssemblyName(assemblyName); } } class Program { static void Main(string[] args) { // 初始化自定义加载上下文 var loadContext = new CustomDllLoadContext("./你的子文件夹名称"); // 提前加载目标DLL var dll1Assembly = loadContext.LoadFromAssemblyName(new AssemblyName("dll1")); // 后续使用dll1中的类型时,通过该程序集获取实例 Type targetType = dll1Assembly.GetType("dll1.你的类名"); object instance = Activator.CreateInstance(targetType); // 执行类中的方法等操作 } }
方法3:通过.csproj配置私有探测路径
在控制台程序的项目文件中添加以下配置,指定依赖的探测目录:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp3.1</TargetFramework> <ProbingPath>你的子文件夹名称</ProbingPath> </PropertyGroup> <ItemGroup> <PackageReference Include="dll1" Version="6.0.0" PrivateAssets="all" /> </ItemGroup> </Project>
<ProbingPath>告诉运行时优先去指定子文件夹查找依赖。<PrivateAssets="all">确保dll1不会被自动复制到父目录,保持在子文件夹中。
额外注意事项
- 确认子文件夹中
dll1的所有依赖项都齐全,避免加载失败。 - 如果遇到版本绑定冲突,可在程序根目录创建
app.config添加重定向配置:
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="dll1" publicKeyToken="你的DLL公钥令牌" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-5.9.9.9" newVersion="6.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
内容的提问来源于stack exchange,提问作者Alexel37
相关产品推荐
相关产品推荐

