You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core下Dll Hell问题:.NET6程序被.NET3.1开源EXE加载报错

解决方法

1. 用AssemblyLoadContext隔离加载你的.NET 6组件

自定义一个程序集加载上下文,强制从你的项目输出目录加载依赖DLL,避免和开源EXE的加载上下文冲突:

using System.Runtime.Loader;
using System.IO;

public class CustomAssemblyLoadContext : AssemblyLoadContext
{
    private readonly string _loadDir;

    public CustomAssemblyLoadContext(string assemblyPath) : base(isCollectible: false)
    {
        _loadDir = Path.GetDirectoryName(assemblyPath);
    }

    protected override Assembly Load(AssemblyName assemblyName)
    {
        // 优先从自身目录加载目标DLL
        var dllPath = Path.Combine(_loadDir, $"{assemblyName.Name}.dll");
        if (File.Exists(dllPath))
        {
            return LoadFromAssemblyPath(dllPath);
        }
        // 其他依赖回退到默认加载逻辑
        return Default.LoadFromAssemblyName(assemblyName);
    }
}

// 加载组件时使用该上下文
var componentPath = Path.Combine(Directory.GetCurrentDirectory(), "YourNet6Component.dll");
var loadContext = new CustomAssemblyLoadContext(componentPath);
var targetAssembly = loadContext.LoadFromAssemblyPath(componentPath);
// 后续创建实例或调用方法
var instance = targetAssembly.CreateInstance("YourNamespace.YourClass");

2. 手动设置DLL加载优先级

把你的.NET 6项目输出的所有依赖DLL(含6.x版本的System.Linq.dll)放到指定目录,在启动开源EXE前设置环境变量,让CLR优先从该目录加载:

set PATH=你的组件输出目录;%PATH%

如果能在加载前通过代码设置:

Environment.SetEnvironmentVariable("PATH", $"你的组件输出目录;{Environment.GetEnvironmentVariable("PATH")}");

3. 用runtimeconfig.json指定依赖版本

为你的组件创建YourNet6Component.runtimeconfig.json,明确指定依赖的System.Linq版本为6.x,确保加载时解析到正确版本:

{
  "runtimeOptions": {
    "tfm": "net6.0",
    "framework": {
      "name": "Microsoft.NETCore.App",
      "version": "6.0.0"
    },
    "dependencies": {
      "System.Linq": {
        "version": "6.0.0"
      }
    }
  }
}

将该文件和你的组件DLL放在同一目录。

4. 替换.NET 6新增方法为兼容实现

如果以上方法无效,可临时修改代码,把DistinctBy替换成.NET Core 3.1兼容的自定义扩展方法:

public static class EnumerableExtensions
{
    public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
    {
        if (source == null) throw new ArgumentNullException(nameof(source));
        if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
        
        var seenKeys = new HashSet<TKey>();
        foreach (var element in source)
        {
            var key = keySelector(element);
            if (seenKeys.Add(key))
            {
                yield return element;
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者agarwal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 20:57:27