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文件生成过去 解决方法:手动拷贝过去,或者设置成自动生成过 ...
随机推荐
- centos 7.0运行docker出现内核报错解决方法
目前我这里docker是运行在centos 7.0系统里,使用1.5版本docker,最近一台服务器总是不定期死机,通过查看日志发现属于内核bug导致,报错信息如下 1 2 3 4 5 6 7 8 9 ...
- #Week4 Logistic Regression
一.Classification 主要讨论二元分类. 线性回归处理分类问题显然不靠谱,所以采用逻辑回归. 二.Hypothesis Representation 假设函数变为\(h_\theta(x) ...
- 一文揭秘测试平台中是如何将测试用例一键转化Jmeter压测脚本
接上篇,一键转化将接口测试平台测试用例转化成Jmeter压测脚本思路,这里我首先在java 上面做了一个简单的实验,看看 转化的中间遇到的问题,这里呢,我只是给了一个简单的demo 版本, ...
- Codeforce 1255 Round #601 (Div. 2) A. Changing Volume (贪心)
Bob watches TV every day. He always sets the volume of his TV to bb. However, today he is angry to f ...
- qt creator源码全方面分析(4-3)
内外命名空间 QtCreator源码中,每一个子项目都有内外两层命名空间,一个是外部的,一个是内部的. 示例如下 namespace ExtensionSystem { namespace Inter ...
- C#并发编程之初识并行编程
写在前面 之前微信公众号里有一位叫sara的朋友建议我写一下Parallel的相关内容,因为手中商城的重构工作量较大,一时之间无法抽出时间.近日,这套系统已有阶段性成果,所以准备写一下Parallel ...
- Re模块的方法补充
id_str = input("输入一个身份证号:") import re obj = re.compile(r"^([1-9]\d{16}[0-9x]|[1-9]\d{ ...
- [hdu1532]最大流
裸最大流,求最大流一般步骤如下: (1)所有正向边权初始化为容量,反向边权初始化为0 (2)找增广路 (3)找到则进入(4),否则得到最大流并退出 (4) 增广路上所有边减去最小边权,相应的方向边加上 ...
- leeCode刷题 lc184
Employee 表包含所有员工信息,每个员工有其对应的 Id, salary 和 department Id. +----+-------+--------+--------------+| Id ...
- Spring Boot Admin实现服务健康预警
Over View 上一篇文章主要介绍了Spring Boot Admin的概况以及我们如何在系统中引入和使用Spring Boot Admin,以此来帮助我们更加了解自己的系统,做到能快速发现.排查 ...