首页 > 解决方案 > System.Configuration.ConfigurationManager 与 Microsoft.Extensions.Configuration

问题描述

我正在开发一个类库(.NET Standard 2.0)CL,我们的一些遗留项目(.NET Framework 4.6.1)LP 和我们的许多新实现(.NET Core 3.1)NI 将使用它。

我的类库 CL 需要一些配置设置,但是当它被新的实现 NI 使用时,CL 接收Microsoft.Extensions.Configuration.IConfiguration,就像 NI 一样appSettings.json

当从遗留项目 LP 中使用时,CL 接收System.Configuration.ConfigurationManager.AppSettings为 LP 具有web.configapp.config.

是否有任何优雅的方法可以从 .NET Framework 或 .NET Core 两种类型的项目中读取配置?我不想阅读像 LP 或 NI 这样正在使用我的库 CL 的项目中的配置,因为该配置对他们没有用。

private static void LoadConfiguration() // called from constructor
{
  string receivedFromNETCore = configuration["DataMappingXml"]; 
  // Microsoft.Extensions.Configuration.IConfiguration    
  string receivedFromNETFramework = 
  ConfigurationManager.AppSettings["DataMappingXml"];
    
  // TODO: LOAD configuration and process.
}

标签: .net-core.net-standard-2.0configurationmanager.net-framework-4.8microsoft.extensions.configuration

解决方案


推荐的方法是通过以下步骤迁移到Microsoft.Extensions.Configurationfrom :System.Configuration.ConfigurationManager

  1. 安装 Microsoft.Extensions.Configuration 并创建自定义配置提供程序
  2. 删除对 System.Configuration.ConfigurationManager 的任何静态引用
  3. 将 web.config 和 app.config 转换为 appsettings.json
  4. 重构为强类型配置类

此迁移的详细描述由 Alexander Slotte 在本文中给出:将 .NET Framework 中的配置迁移到 .NET Core


推荐阅读