ASP.NET Core - 配置系统之自定义配置提供程序

ASP.NET Core - 配置系统之自定义配置提供程序

  • 4. 自定义配置提供程序
    • IConfigurationSource
    • IConfigurationProvider

4. 自定义配置提供程序

在 .NET Core 配置系统中封装一个配置提供程序关键在于提供相应的 IconfigurationSource 实现和 IConfigurationProvider 接口实现,这两个接口在上一章 ASP.NET Core - 配置系统之配置提供程序 中也有提到了。

IConfigurationSource

IConfigurationSource 负责创建 IConfigurationProvider 实现的实例。它的定义很简单,就一个Build方法,返回 IConfigurationProvider 实例:

public interface IConfigurationSource
{IConfigurationProvider Build(IConfigurationBuilder builder);
}

IConfigurationProvider

IConfigurationProvider 负责实现配置的设置、读取、重载等功能,并以键值对形式提供配置。

public interface IConfigurationProvider
{// 获取指定父路径下的直接子节点Key,然后 Concat(earlierKeys) 一同返回IEnumerable<string> GetChildKeys(IEnumerable<string> earlierKeys, string parentPath);// 当该配置提供程序支持更改追踪(change tracking)时,会返回 change token// 否则,返回 nullIChangeToken GetReloadToken();// 加载配置void Load();// 设置 key:valuevoid Set(string key, string value);// 尝试获取指定 key 的 valuebool TryGet(string key, out string value);
}

像工作中常用的配置中心客户端,例如 nacos、consul,都是实现了对应的配置提供程序,从而将配置中心中的配置无缝地接入到 .NET Core 的配置系统中进行使用,和本地配置文件的使用没有分别。

如果我们需要封装自己的配置提供程序,推荐直接继承抽象类 ConfigurationProvider,该类实现了 IConfigurationProvider 接口,继承自该类只要实现 Load 方法即可,Load 方法用于从配置来源加载解析配置信息,将最终的键值对配置信息存储到 Data 中。这个过程中可参考一下其他已有的配置提供程序的源码,模仿着去写自己的东西。

在我们日常的系统平台中,总少不了数据字典这样一个功能,用于维护平台中一些业务配置,因为是随业务动态扩展和变动的,很多时候不会写在配置文件,而是维护在数据库中。以下以这样一个场景实现一个配置提供程序。

因为是以数据库作为载体来存储配置信息,所以第一步就是定义实体类

public class DataDictioaryDO
{public int Id { get; set; }public int? ParentId { get; set; }public string Key { get; set; }public string Value { get; set; }
}

数据字典支持多级级联,通过 ParentId 关联上一级,ParentId 为空的即为根节点,如存在下级节点则 Value 值可以为空,就算填写了也无效,最终呈现出来的就是一个树结构。

然后就是定义相应的数据库访问上下文 DataDictionaryDbContext

public class DataDictionaryDbContext : DbContext
{public DbSet<DataDictioaryDO> DataDictioaries { get; set; }public DataDictionaryDbContext(DbContextOptions<DataDictionaryDbContext> options) : base(options){}protected override void OnModelCreating(ModelBuilder modelBuilder){base.OnModelCreating(modelBuilder);modelBuilder.Entity<DataDictioaryDO>().HasKey(e => e.Id);modelBuilder.Entity<DataDictioaryDO>().Property(e => e.Value).IsRequired(false);}
}

通过 DbContextOptions 交由外部去配置具体的数据库类型和连接字符串。

之后创建 IConfigurationSource 实现类,主要就是构造函数中需要传入数据库配置委托,并且在 Build 实例化EFDataDictionaryConfigurationProvider 对象。

public class EFDataDictionaryConfigurationSource : IConfigurationSource
{private readonly Action<DbContextOptionsBuilder> _action;public EFDataDictionaryConfigurationSource(Action<DbContextOptionsBuilder> action){_action= action;}public IConfigurationProvider Build(IConfigurationBuilder builder){return new EFDataDictionaryConfigurationProvider(_action);}
}

之后通过继承 ConfigurationProvider 实现 EFDataDictionaryConfigurationProvider,主要逻辑就是从数据库获取对应的数据表,如果表中没有数据则插入默认数据,再通过相应的解析器解析数据表数据生成一个 Dictionary<string, string> 对象。

public class EFDataDictionaryConfigurationProvider : ConfigurationProvider
{Action<DbContextOptionsBuilder> OptionsAction { get; }public EFDataDictionaryConfigurationProvider(Action<DbContextOptionsBuilder> action){OptionsAction = action;}public override void Load(){var builder = new DbContextOptionsBuilder<DataDictionaryDbContext>();OptionsAction(builder);using var dbContext = new DataDictionaryDbContext(builder.Options);if(dbContext == null){throw new Exception("Null DB Context !");}dbContext.Database.EnsureCreated();if (!dbContext.DataDictioaries.Any()){CreateAndSaveDefaultValues(dbContext);}Data = EFDataDictionaryParser.Parse(dbContext.DataDictioaries);}private void CreateAndSaveDefaultValues(DataDictionaryDbContext context){var datas = new List<DataDictioaryDO>{new DataDictioaryDO{Id = 1,Key = "Settings",},new DataDictioaryDO{Id = 2,ParentId = 1,Key = "Provider",Value = nameof(EFDataDictionaryConfigurationProvider)},new DataDictioaryDO{ Id = 3,ParentId = 1,Key = "Version",Value = "v1.0.0"}};context.DataDictioaries.AddRange(datas);context.SaveChanges();}
}

其中,解析器 EFDataDictionaryParser 的代码如下,主要就是通过递归的方式,通过树形数据的 key 构建完整的 key,并将其存入 Dictionary<string,string> 对象中。

internal class EFDataDictionaryParser
{private readonly IDictionary<string, string> _data = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase);private readonly Stack<string> _context = new();private string _currentPath;private EFDataDictionaryParser() { }public static IDictionary<string, string> Parse(IEnumerable<DataDictioaryDO> datas) =>new EFDataDictionaryParser().ParseDataDictionaryConfiguration(datas);private IDictionary<string, string> ParseDataDictionaryConfiguration(IEnumerable<DataDictioaryDO> datas){_data.Clear();if(datas?.Any() != true){return _data;}var roots = datas.Where(d => !d.ParentId.HasValue);foreach (var root in roots){EnterContext(root.Key);VisitElement(datas, root);ExitContext();}return _data;}private void VisitElement(IEnumerable<DataDictioaryDO> datas, DataDictioaryDO parent){var children = datas.Where(d => d.ParentId == parent.Id);if (children.Any()){foreach (var section in children){EnterContext(section.Key);VisitElement(datas, section);ExitContext();}}else{var key = _currentPath;if (_data.ContainsKey(key))throw new FormatException($"A duplicate key '{key}' was found.");_data[key] = parent.Value;}}private void EnterContext(string context){_context.Push(context);_currentPath = ConfigurationPath.Combine(_context.Reverse());}private void ExitContext(){_context.Pop();_currentPath = ConfigurationPath.Combine(_context.Reverse());}
}

之后为这个配置提供程序提供一个扩展方法,方便之后的使用,如下:

public static class EFDataDictionaryConfigurationExtensions
{public static IConfigurationBuilder AddEFDataDictionaryConfiguration(this IConfigurationBuilder builder, Action<DbContextOptionsBuilder> optionAction){builder.Add(new EFDataDictionaryConfigurationSource(optionAction));return builder;}
}

之后在入口文件中将我们的配置扩展程序添加到配置系统中,并指定使用内存数据库进行测试

using ConfigurationSampleConsole.ConfigProvider;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;using var host = Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((context, config) =>{// 清除原有的配置提供程序config.Sources.Clear();config.AddEFDataDictionaryConfiguration(builder =>{builder.UseInMemoryDatabase("DataDictionary");});}).Build();var configuration = host.Services.GetService<IConfiguration>();Console.WriteLine($"Settings:Provider: {configuration.GetValue<string>("Settings:Provider")}");
Console.WriteLine($"Settings:Version: {configuration.GetValue<string>("Settings:version")}");host.Run();

最后的控制台输出结果如下:

在这里插入图片描述
以上就是 .NET Core 框架下配置系统的一部分知识点,更加详尽的介绍大家可以再看看官方文档。配置系统很多时候是结合选项系统一起使用的,下一篇将介绍一下 .NET Core 框架下的选项系统。



参考文章:

ASP.NET Core 中的配置 | Microsoft Learn
配置 - .NET | Microsoft Learn
理解ASP.NET Core - 配置(Configuration)



ASP.NET Core 系列总结:

目录:ASP.NET Core 系列总结
上一篇:ASP.NET Core — 配置系统之配置提供程序
下一篇:ASP.NET Core — 选项系统之选项配置

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/3942.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

gitlab runner正常连接 提示 作业挂起中,等待进入队列 解决办法

方案1 作业挂起中,等待进入队列 重启gitlab-runner gitlab-runner stop gitlab-runner start gitlab-runner run方案2 启动 gitlab-runner 服务 gitlab-runner start成功启动如下 [rootdocserver home]# gitlab-runner start Runtime platform …

python爬虫报错日记

python爬虫报错日记 类未定义 原因&#xff1a;代码检查没有问题**&#xff0c;位置错了**&#xff0c;测试代码包含在类里…… UnicodedecodeError错误 原因&#xff1a;字符没有自动转换成utf-8格式 KeyError&#xff1a;“href” 原因&#xff1a;前面运行正常&#x…

简历_基于 Cache Aside 模式解决数据库与缓存一致性问题。

系列博客目录 文章目录 系列博客目录缓存更新策略总结案例&#xff1a;给查询商铺的缓存添加超时剔除和主动更新的策略 说到解决数据库与缓存一致性的问题&#xff0c;其实就是要解决缓存更新的问题。 缓存更新策略 业务场景: 低一致性需求:使用内存淘汰机制。例如店铺类型的…

UllnnovationHub,一个开源的WPF控件库

目录 UllnnovationHub1.项目概述2.开发环境3.使用方法4.项目简介1.WPF原生控件1.Button2.GroupBox3.TabControl4.RadioButton5.SwitchButton6.TextBox7.PasswordBox8.CheckBox9.DateTimePicker10.Expander11.Card12.ListBox13.Treeview14.Combox15.Separator16.ListView17.Data…

二进制/源码编译安装mysql 8.0

二进制方式&#xff1a; 1.下载或上传安装包至设备&#xff1a; 2.创建组与用户&#xff1a; [rootopenEuler-1 ~]# groupadd mysql [rootopenEuler-1 ~]# useradd -r -g mysql -s /bin/false mysql 3.解压安装包&#xff1a; tar xf mysql-8.0.36-linux-glibc2.12-x86_64.ta…

快速入门:如何注册并使用GPT

文章目录 ProtonMail邮箱步骤 1&#xff1a;访问Proton官网步骤 2&#xff1a;创建ProtonMail账户步骤 3&#xff1a;选择注册免费账户步骤 4&#xff1a;填写邮箱地址和手机号&#xff08;可选&#xff09;步骤 5&#xff1a;邮箱验证&#xff08;必须进行验证&#xff09;步骤…

迅为瑞芯微RK3562开发板/核心板应用于人脸跟踪、身体跟踪、视频监控、自动语音识别(ASR)、图像分类驾驶员辅助系统(ADAS)...

可应用于人脸跟踪、身体跟踪、视频监控、自动语音识别(ASR)、图像分类驾驶员辅助系统(ADAS)、车牌识别、物体识别等。iTOP-3562开发板/核心板采用瑞芯微RK3562处理器&#xff0c;内部集成了四核A53Mali G52架构&#xff0c;主频2GHZ&#xff0c;内置1TOPSNPU算力&#xff0c;RK…

Mybatis Plus 分页实现

目录 前言&#xff1a; 一、分页插件 1、添加配置类 &#xff08;1&#xff09;创建配置类方式: &#xff08;2&#xff09;启动类中配置分页插件方式(推荐): 2、测试 二、XML自定义分页 1、UserMapper中定义接口方法 2、UserMapper.xml中编写SQL ​编辑 3、测试 前…

20250118-读取并显示彩色图像以及提取彩色图像的 R、G、B 分量

读取并显示彩色图像以及提取彩色图像的 R、G、B 分量 import cv2 #彩图R、G、B的提取 import torch from PIL import Image from matplotlib import pyplot as plt import numpy as np读取并显示彩色图像的三种方法&#xff1a; img_path "./data/yndx"1.1 使用 …

Android BitmapShader实现狙击瞄具十字交叉线准星,Kotlin

Android BitmapShader实现狙击瞄具十字交叉线准星&#xff0c;Kotlin <?xml version"1.0" encoding"utf-8"?> <RelativeLayout xmlns:android"http://schemas.android.com/apk/res/android"xmlns:tools"http://schemas.android.…

20250118拿掉荣品pro-rk3566开发板上Android13下在uboot和kernel启动阶段的Rockchip这个LOGO标识

20250118拿掉荣品pro-rk3566开发板上Android13下在uboot和kernel启动阶段的Rockchip这个LOGO标识 2025/1/18 15:12 缘起&#xff1a;做飞凌OK3588-C开发板/核心板【Linux R4】的时候&#xff0c;测试/生产要求没有开机LOGO【飞凌/Rockchip】 要求&#xff1a;黑屏或者中性界面。…

浙江安吉成新照明电器:Acrel-1000DP 分布式光伏监控系统应用探索

安科瑞吕梦怡 18706162527 摘 要&#xff1a;分布式光伏发电站是指将光伏发电组件安装在用户的建筑物屋顶、空地或其他适合的场地上&#xff0c;利用太阳能进行发电的一种可再生能源利用方式&#xff0c;与传统的大型集中式光伏电站相比&#xff0c;分布式光伏发电具有更灵活…

QQ邮箱登录逆向

文章目录 抓包密码p的加密算法1.全局搜索参数2.加密函数 抓包 输入账号和错误的密码,可用看到如下的两个包: check: 里面包含密码加密时需要的参数及发送登录时需要的参数 check的响应: ptui_checkVC(0, !UIO, \x00\x00\x00\x00\x74\xca\x4f\x59, ef787cccd192b4015ef02ef3…

Docker安装PostGreSQL docker安装PostGreSQL 完整详细教程

Docker安装PostGreSQL docker安装PostGreSQL 完整详细教程 Docker常用命令大全Docker 运行命令生成Docker 上安装 PostGreSQL 14.15 的步骤&#xff1a;1、拉取 PostGreSQL 14.15 镜像2、创建并运行容器3、测试连接4、设置所有IP都可以运行连接进入容器内 修改配置文件关闭容器…

常见的两种虚拟化技术比较:KVM与VMware

引言 在当今的数据中心和云计算环境中&#xff0c;虚拟化技术已经成为不可或缺的一部分。它不仅提高了资源利用率&#xff0c;降低了硬件成本&#xff0c;还增强了系统的灵活性和可管理性。KVM&#xff08;基于内核的虚拟机&#xff09;和VMware是两种广泛使用的虚拟化解决方案…

Redis的安装和使用--Windows系统

Redis下载地址&#xff1a; windows版本readis下载&#xff08;GitHub&#xff09;&#xff1a; https://github.com/tporadowski/redis/releases &#xff08;推荐使用&#xff09; https://github.com/MicrosoftArchive/redis/releases 官网下载&#xff08;无Windows版本…

Spring Security(maven项目) 3.0.2.5版本中改

前言&#xff1a; 通过实践而发现真理&#xff0c;又通过实践而证实真理和发展真理。从感性认识而能动地发展到理性认识&#xff0c;又从理性认识而能动地指导革命实践&#xff0c;改造主观世界和客观世界。实践、认识、再实践、再认识&#xff0c;这种形式&#xff0c;循环往…

flutter 装饰类【BoxDecoration】

装饰类 BoxDecoration BoxDecoration 是 Flutter 中用于控制 Container 等组件外观的装饰类&#xff0c;它提供了丰富的属性来设置背景、边框、圆角、阴影等样式。 BoxDecoration 的主要属性 1.color 背景颜色。类型&#xff1a;Color?示例&#xff1a; color: Colors.blu…

ScratchLLMStepByStep:训练自己的Tokenizer

1. 引言 分词器是每个大语言模型必不可少的组件&#xff0c;但每个大语言模型的分词器几乎都不相同。如果要训练自己的分词器&#xff0c;可以使用huggingface的tokenizers框架&#xff0c;tokenizers包含以下主要组件&#xff1a; Tokenizer: 分词器的核心组件&#xff0c;定…

抖音a_bogus,mstoken全参数爬虫逆向补环境2024-06-15最新版

抖音a_bogus,mstoken全参数爬虫逆向补环境2024-06-15最新版 源码获取 已放在github上&#xff0c;抖音部分已全面更新为a_bogus算法。 除了抖音还包括快手&#xff0c;小红书&#xff0c;哔哩哔哩&#xff0c;微博&#xff0c;京东&#xff0c;淘宝等平台&#xff0c;旨在帮助…