【问题标题】:System.Configuration.ConfigurationManager vs Microsoft.Extensions.ConfigurationSystem.Configuration.ConfigurationManager 与 Microsoft.Extensions.Configuration
【发布时间】:2021-07-21 10:21:09
【问题描述】:

我正在开发一个类库 (.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.0 configurationmanager .net-framework-4.8 microsoft.extensions.configuration


    【解决方案1】:

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

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

    Alexander Slotte 在这篇文章中给出了这个迁移的详细描述:Migrating configuration in .NET Framework to .NET Core

    【讨论】:

      猜你喜欢
      • 2010-10-25
      • 2023-03-07
      • 2022-01-23
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 2019-02-08
      • 2022-06-10
      相关资源
      最近更新 更多