.net-core - 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.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.
}
解决方案
推荐的方法是通过以下步骤迁移到Microsoft.Extensions.Configuration
from :System.Configuration.ConfigurationManager
- 安装 Microsoft.Extensions.Configuration 并创建自定义配置提供程序
- 删除对 System.Configuration.ConfigurationManager 的任何静态引用
- 将 web.config 和 app.config 转换为 appsettings.json
- 重构为强类型配置类
此迁移的详细描述由 Alexander Slotte 在本文中给出:将 .NET Framework 中的配置迁移到 .NET Core
推荐阅读
- ruby - 使用 Ruby 服务器作为 API 中间人
- python-3.x - 熊猫向前向后填充列级别内的列
- ios - iOS - 在后台推送通知上刷新数据(发出 Api 请求)
- powerquery - Power Query 将列表中的记录转换为列
- javascript - d3js 版本 3 到 4 用于切换条形图
- asynchronous - UWP:抛出/引发不会导致应用程序崩溃,异常被忽略
- javascript - 警告:函数作为反应子问题无效......是因为我的容器吗?
- vim - 当我退出插入模式时,如何防止 Vim 复制我的文本?
- excel - 如何将多行合并为一行
- javascript - 请帮助我使用 javascript 构建 Hard Drop 功能(俄罗斯方块)