System.Configuration.ConfigurationManager 与 Microsoft.Extensions.Configuration

use*_*482 5 configurationmanager .net-core .net-standard-2.0 .net-4.8 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.config之一app.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.
}
Run Code Online (Sandbox Code Playgroud)

Tys*_*bby 1

解决此问题的推荐方法是将所有System.Configuration.ConfigurationManager引用替换为 Microsoft.Extensions.Configuration引用,然后从 ASP.NET 迁移到 ASP.NET Core。Microsoft 关于迁移的文章:从 ASP.NET 迁移到 ASP.NET Core

如果您无法进行迁移,您可以尝试平台多目标: 从 .NET Framework 迁移到 .NET Core