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

.NET6迁移后加载System.Runtime.dll失败及ConfigurationManager替代方案咨询

问题解决方案

核心原因

.NET 6(及.NET Core系列)的配置系统与.NET Framework的ConfigurationManager机制存在本质差异,当.NET Standard组件被.NET 6项目引用时,原依赖System.Configuration的代码会因运行环境变化,无法正确加载配置相关的.NET 6程序集,进而抛出System.Runtime.dll加载异常。

替代方案

1. 迁移至.NET现代配置系统(推荐)

改用.NET Core/.NET 6原生的IConfiguration系统,跨平台兼容且支持多配置源:

  • 在.NET Standard项目中安装Microsoft.Extensions.Configuration系列NuGet包(如Microsoft.Extensions.Configuration.Json、Microsoft.Extensions.Configuration.Xml等,按需选择)
  • 重构配置加载逻辑:
    • 非依赖注入场景(如控制台、工具类):
      var configBuilder = new ConfigurationBuilder()
          .SetBasePath(AppContext.BaseDirectory)
          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
      
      IConfiguration configuration = configBuilder.Build();
      // 读取配置示例
      var apiUrl = configuration["ApiSettings:BaseUrl"];
      
    • 依赖注入场景(如ASP.NET Core):
      private readonly IConfiguration _config;
      
      public YourClass(IConfiguration config)
      {
          _config = config;
      }
      
      // 使用配置
      var timeout = _config.GetValue<int>("AppSettings:RequestTimeout");
      

2. 条件编译兼容双框架

若需保留原有逻辑并兼容.NET 6,可通过条件编译区分处理:

  • 在.NET Standard项目的.csproj中添加框架条件定义:
    <PropertyGroup>
        <DefineConstants Condition="'$(TargetFramework)' == 'netstandard2.0'">NETSTANDARD2_0</DefineConstants>
        <DefineConstants Condition="'$(TargetFramework)' == 'net6.0'">NET6_0</DefineConstants>
    </PropertyGroup>
    
  • 代码中分支处理:
    #if NETFRAMEWORK
        config = ConfigurationManager.OpenExeConfiguration(GetType().Assembly.Location);
    #elif NETSTANDARD || NET6_0
        // 使用.NET现代配置逻辑
        var configuration = new ConfigurationBuilder()
            .SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: true)
            .Build();
        // 按需封装配置对象,适配原有代码逻辑
    #endif
    

3. 兼容包过渡方案(不推荐长期使用)

通过微软官方兼容包临时保留ConfigurationManager用法:

  • 在.NET 6项目中安装System.Configuration.ConfigurationManager NuGet包
  • 确保配置文件(如app.config)放置在正确目录,且格式符合.NET Framework规范
  • 此方案仅适用于短期过渡,长期仍建议迁移至现代配置系统

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:05:06