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文件生成过去 解决方法:手动拷贝过去,或者设置成自动生成过 ...
随机推荐
- 自动安装带nginx_upstream_check_module模块的Nginx脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 #!/bin/bash useradd -s /sbin/no ...
- unittest(生成 HTMLTestRunner 模块)
一:生成 HTMLTestRunner 模块 unittest 里面是不能生成 html 格式报告的,需要导入一个第三方的模块:HTMLTestRunner 方法1.这个模块下载不能通过 pip 安装 ...
- POJ 2777——线段树Lazy的重要性
POJ 2777 Count Color --线段树Lazy的重要性 原题 链接:http://poj.org/problem?id=2777 Count Color Time Limit: 1000 ...
- libevent(二)尾队列 && 最小堆
本文主要研究libevent中用来存储事件的两个结构体. 尾队列 具体定义位于queue.h中. #define TAILQ_HEAD(name, type) \ struct name { \ st ...
- file download hash mismatch
在linux中使用cmake时,遇到了"file download hash mismatch",同时status显示"unsupported protocol" ...
- Java种sleep和wait的区别
1,sleep方法是Thread类的静态方法,wait()是Object超类的成员方法 2,sleep()方法导致了程序暂停执行指定的时间,让出cpu该其他线程,但是他的监控状态依然保持者,当指定的时 ...
- 【HBase】快速搞定HBase与Hive的对比、整合
目录 对比 整合 需求一 步骤 一.将HBase的五个jar包拷贝到Hive的lib目录下 二.修改hive的配置文件 三.在Hive中建表 四.创建hive管理表与HBase映射 五.在HBase中 ...
- Code Review 常见的5个错误模式
原作者:Trisha Gee Code Review 的时候,每个人都会关心最佳实践,但最坏的实践有时可能会更有启示意义. Code Review是研发团队必不可少的,但并不总是正确的.这篇文章指出了 ...
- 基于 abp vNext 和 .NET Core 开发博客项目
项目介绍 此个人博客项目底层基于 ABP Framework (不完全依赖)搭建项目 和免费开源跨平台的 .NET Core 3.1 开发,可作为 .NET Core 入门项目进行学习,支持各种主流数 ...
- 通过 docker images 获取 Dockerfile
通过docker image 获取到 dockerfile docker history --format {{.CreatedBy}} --no-trunc=true $DockerImage |s ...