最近在写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的另外一种思路(全局,实时变化无需重启项目)的更多相关文章

  1. asp.net core读取appsetting.json文件

    1.在Startup.cs文件中注入,ConfigureServices方法 services.Configure<MyConfig>(Configuration.GetSection(& ...

  2. .net core 读取appsetting.json

    1.在appsetting.json 文件中添加自定义配置 { "Logging": { "LogLevel": { "Default": ...

  3. NetCore 获取appsetting.json 文件中的配置

    1. using Microsoft.Extensions.Configuration public class HomeController : Controller { public IConfi ...

  4. asp.net core获取自定义json的配置内容

    首先在主目录下建立:Iyibank.Web.json文件 里边的内容如下: { "ConnectionStrings": { "RedisCache": &qu ...

  5. 解决.net core读取appSetting.json文件中文字符乱码

    如上所诉 vs菜单栏中  :工具 =>自定义 => 命令 =>添加命令 =>文件 =>找到高级保存选项点击 然后关闭,这时在visual studio界面就会有高级保存选 ...

  6. asp.net core 获取appsettings.json里的配置

    public GoodsController(IConfiguration configuration) { Configuration = configuration; UpFileDir = Co ...

  7. 通过Class获取标签,兼容的几种思路

    在js中通过document.getElementsByClassName()在低版本IE浏览器中不兼容.然后我写了几种方案,大家可以参考参考. html代码 <!DOCTYPE html> ...

  8. .Net Core 实践 - 如何在控制台应用(.Net Core)使用appsettings.json配置

    新建控制台应用(.Net Core)程序 添加json文件,命名为appsettings.json,设置文件属性 如果较新则复制.添加内容如下 { "MyWords" : &quo ...

  9. 在abp core中出现运行项目时EF获取到的appsetting.json或者appsettings.Production.json中的连接字符串为空

    原因:有可能是生成的bin或者debug文件夹下没有将appsetting.json或者appsettings.Production.json文件生成过去 解决方法:手动拷贝过去,或者设置成自动生成过 ...

随机推荐

  1. Clickhouse 字符串拆分 OR 一行转多行

    Clickhouse 字符串拆分 OR 一行转多行 我想把 '123_456_142354_23543' 通过'_' 下划线进行拆分成

  2. 代码,绘画,设计常用的颜色名称-16进制HEX编码-RGB编码 对照一览表

    排列方式,英文名称的字典序 颜色名 HEX16进制编码 RGB编码 AliceBlue F0F8FF 240,248,255 AntiqueWhite FAEBD7 250,235,215 Aqua ...

  3. Codeforce-CodeCraft-20 (Div. 2)-B. String Modification (找规律+模拟)

    Vasya has a string s of length n. He decides to make the following modification to the string: Pick ...

  4. Java中常用的获取从当前月开始的前第i个月、取结束时间与开始时间相差多少个月份等的方法

    @RunWith(SpringRunner.class) @SpringBootTest public class DateTest { @Test public void test(){ DateF ...

  5. IoTClientTool自动升级更新

    IoTClientTool是什么 IoTClientTool是什么,IoTClientTool是IoTClient开源组件的可视化操的作实现.方便对plc设备和ModBusRtu.BACnet.串口等 ...

  6. Java——Spring超详细总结

    Spring概述 一.简化Java开发 Spring为了降低Java开发的复杂性,采用了以下四种策略 基于POJO的轻量级和最小侵入性编程: 通过依赖注入和面向接口实现松耦合: 基于切面和惯例进行声明 ...

  7. 数位dp H - F(x) HDU - 4734

    http://acm.hdu.edu.cn/showproblem.php?pid=4734 一般数位dp表示的是数的性质,这个题目也是一样,但是我们求出来的是一个函数的值,怎么把这个值转化成一类数, ...

  8. dbcp数据源连接池

    一.数据源连接池 我们之前利用jdbc连接数据库,每次都要创建连接对象,销毁连接对象,如果并发访问量比较大,这样肯定比较辣 浪费数据库的效率,我们可以像之前mybatis中缓存查询到的数据一样,可以把 ...

  9. CF-448C Painting Fence 分治

    Painting fence 题意 乍一看以为是之前做过的一道单调队列优化的DP,不是. 也是有n块木板,每个木板宽1米,有一个高度ai,现在要把他们刷成橘色,给了你一个宽一米的刷子,你可以横着刷,或 ...

  10. SpringBoot2.0 @Cacheable 添加超时策略

    SpringBoot2.0 @Cacheable 添加超时策略 逻辑比较简单,废话不多说,直接进入正题: 需求:SpringBoot 利用注解使缓存支持过期时间 (同@Cacheable @Cache ...