net core获取appsetting.json的另外一种思路(全局,实时变化无需重启项目)
最近在写net core的项目,在非controller和service里面需要用到appsetting.json文件里面的一些配置,查资料大概有几种思路:
- 注入,然后config.GetSection("xxx")
- 写一个监听,filewatch,去监听appsetting.json的变化,读取key-value。
- 工具类里面传入再走一遍 new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)
- 使用IOptions<TOptions>,创建对应的实体类
我在查资料的时候发现了一个IOptionsMonitor<T>,这个可以监听到文件的变化,结合IOptionsMonitor<T>,我写了一个工具类,具体使用办法如下:
(1)创建appsetting.json对应的实体类文件,属性的名字要与配置文件里面的一一对应。
public class AllSetting
{
///// <summary>
///// 数据库配置
///// </summary>
public ConnectionSetting ConnectionStrings { get; set; } ///// <summary>
///// 日志模块
///// </summary>
public LoggingSetting Logging { get; set; } ///// <summary>
///// AllowedHosts
///// </summary>
public string AllowedHosts { get; set; }
}
{
"ConnectionStrings": {
"DefaultConnection": "xxxx"
//"PgSqlConnection": "xxxx",
//"MySqlConnection": "xxxx",
//"OracleConnection": "xxxx"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"Gateway": {
"Uri": "xxxx"
}
}
(2) 编写工具类AppsettingsUtility
/// <summary>
/// 全局获取app的设置工具类
/// </summary>
public class AppsettingsUtility
{
/// <summary>
/// log4net
/// </summary>
private readonly ILog log; /// <summary>
/// serviceProvider
/// </summary>
private static ServiceProvider serviceProvider; /// <summary>
/// _services
/// </summary>
private static IServiceCollection _services; /// <summary>
/// _configuration
/// </summary>
private static IConfiguration _configuration; /// <summary>
/// 初始化工具类
/// </summary>
/// <param name="provider"></param>
public AppsettingsUtility(IServiceCollection services, IConfiguration configuration)
{
_services = services;
_configuration = configuration;
// 仓库名 统一的
log = LogManager.GetLogger("仓库名", typeof(AppsettingsUtility));
if (_services == null || _configuration == null)
{
log.Error("初始化配置工具类发生异常:_services或_configuration为空");
throw new NullReferenceException("初始化配置工具类发生异常");
}
try
{
serviceProvider = _services.BuildServiceProvider();
}
catch (Exception ex)
{
log.Error("_services.BuildServiceProvider()失败:" + ex.ToString());
}
} /// <summary>
/// 获取IOptionsMonitor<T>
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <returns>IOptionsMonitor<T></returns>
public static IOptionsMonitor<T> GetMonitor<T>()
{
if (serviceProvider == null)
{
throw new NullReferenceException("获取失败,ServiceProvider为空");
}
if (typeof(T) != typeof(AllSetting))
{
// TODO: 要限定传递的参数值或者每个setting都注册一遍
}
return serviceProvider.GetRequiredService<IOptionsMonitor<T>>();
} /// <summary>
/// 获取单个的设置实体
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <returns>T</returns>
public static T GetSettingsModel<T>()
{
if (serviceProvider == null)
{
throw new NullReferenceException("获取失败,ServiceProvider为空");
}
if (typeof(T) != typeof(AllSetting))
{
// TODO: 要限定传递的参数值或者每个setting都注册一遍
}
return serviceProvider.GetRequiredService<IOptionsMonitor<T>>().CurrentValue;
} /// <summary>
/// 通过key获取设置
/// </summary>
/// <param name="key">key</param>
/// <returns>设置内容</returns>
public static string GetSetting(string key)
{
if (_configuration == null)
{
throw new NullReferenceException("获取失败,IConfiguration为空");
}
if (string.IsNullOrEmpty(key))
{
throw new NullReferenceException("获取失败,key不能为空");
}
return _configuration.GetSection(key).Value;
}
}
(3)在Startup中注册
// 注入设置类到管道中
services.AddOptions();
services.Configure<AllSetting>(Configuration);
// 初始化工具类
new AppsettingsUtility(services,Configuration);
(4)使用
var aa = AppsettingsUtility.GetMonitor<AllSetting>().CurrentValue;
var bb = AppsettingsUtility.GetSettingsModel<JwtSetting>();
var bb = AppsettingsUtility.GetSetting("Appsetting:xxx");
如果把配置文件改变了,再调用获取设置的时候,设置的值会更新,项目不用重启。这样做对性能的影响没有测试。
如果我这边的思路有什么错误的话,还望批评指出。
net core获取appsetting.json的另外一种思路(全局,实时变化无需重启项目)的更多相关文章
- asp.net core读取appsetting.json文件
1.在Startup.cs文件中注入,ConfigureServices方法 services.Configure<MyConfig>(Configuration.GetSection(& ...
- .net core 读取appsetting.json
1.在appsetting.json 文件中添加自定义配置 { "Logging": { "LogLevel": { "Default": ...
- NetCore 获取appsetting.json 文件中的配置
1. using Microsoft.Extensions.Configuration public class HomeController : Controller { public IConfi ...
- asp.net core获取自定义json的配置内容
首先在主目录下建立:Iyibank.Web.json文件 里边的内容如下: { "ConnectionStrings": { "RedisCache": &qu ...
- 解决.net core读取appSetting.json文件中文字符乱码
如上所诉 vs菜单栏中 :工具 =>自定义 => 命令 =>添加命令 =>文件 =>找到高级保存选项点击 然后关闭,这时在visual studio界面就会有高级保存选 ...
- asp.net core 获取appsettings.json里的配置
public GoodsController(IConfiguration configuration) { Configuration = configuration; UpFileDir = Co ...
- 通过Class获取标签,兼容的几种思路
在js中通过document.getElementsByClassName()在低版本IE浏览器中不兼容.然后我写了几种方案,大家可以参考参考. html代码 <!DOCTYPE html> ...
- .Net Core 实践 - 如何在控制台应用(.Net Core)使用appsettings.json配置
新建控制台应用(.Net Core)程序 添加json文件,命名为appsettings.json,设置文件属性 如果较新则复制.添加内容如下 { "MyWords" : &quo ...
- 在abp core中出现运行项目时EF获取到的appsetting.json或者appsettings.Production.json中的连接字符串为空
原因:有可能是生成的bin或者debug文件夹下没有将appsetting.json或者appsettings.Production.json文件生成过去 解决方法:手动拷贝过去,或者设置成自动生成过 ...
随机推荐
- Computational Geometry
矩形重叠 看过某司一道笔试题:给\(n\)个矩形左下和右上坐标(不能斜放),求重叠最多处矩形个数. 这道题本身不难:可以遍历所有矩形边界组成的点,计算该点被多少矩形包围,从而选出最大值. 由此引申出一 ...
- 一只简单的网络爬虫(基于linux C/C++)————浅谈并发(IO复用)模型
Linux常用的并发模型 Linux 下设计并发网络程序,有典型的 Apache 模型( Process Per Connection ,简称 PPC ), TPC ( Thread Per Conn ...
- 10 微信小程序路由跳转
一.四种跳转方式 API路由详解 除了tabBar这种底部跳转的方法,我们还有路由跳转,以下四种方式: 1. wx.switchTab() :跳转到 tabBar 页面,并关闭其他所有非 tabBar ...
- jmeter的正则表达式编辑器
位置:在后置处理器里面,表示在请求结束或者返回响应结果时发挥作用. 作用:允许用户从服务器的响应中通过使用perl的正则表达式提取值.该元素会作用在指定范围取样器,用正则表达式提取所需值,生成模板字符 ...
- Android EXCEL 解析 xls 和 xlsx,方法其实很简单
前言 Excel 解析,一般来说是在服务端进行的,但是如果移动端要实现解析Excel的功能,那也是有实现的方法的. 不过由于Android 原生用Java/Kotlin实现,所以也可以参考服务端解析E ...
- P1666前缀单词
题目传送门点我传送 Ⅰ.字典树+树型DP 非常奇妙的一种解法 第一部分:构建树 先对来的单词读入,插入字典树 然后对于一颗字典树,其实是有很多无用边的,所以我们需要删去一些边 删去非单词节点和非单词节 ...
- T - zxa and leaf HDU - 5682 二分+dfs
T - zxa and leaf HDU - 5682 题目大意是:给你一颗树,这棵树有些节点已经设置了它的美丽值,然后剩下一些节点需要我们设置美丽值. 一条边的丑陋程度等于被定义为由这个边缘连接的两 ...
- 解决php获取不到Authorization问题
我用的是thinkphp3.2.3, 在使用jwt的时候通过Authorization传递token,但是每次都接收不到,通过修改..htaccess文件,问题成功解决了,下面是的.htaccess文 ...
- 【Swift】获取UILabel中点击的某个功能标签文字并作出响应动作
1.需求 首先.针对UILabel中显示的多个功能标签,作出颜色标记提示. 其次.对关键字作出点击响应动作. 如图所示: 解决: 1.使用正则匹配到关键字 public static var hash ...
- 如何构建一个arm64 AArch64的Ubuntu rootfs
文章目录 1 下载文件创建rootfs文件夹 2 安装qemu-user-static搭建arm64模拟环境 3 chroot 到 模拟arm64的文件系统下 4 安装基础的软件包 5 系统基础的修改 ...