最近在写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. HTML5学习笔记之表格标签

    HTML5学习笔记之表格标签 其他HTML5相关文章 HTML5学习笔记之HTML5基本介绍 HTML5学习笔记之基础标签 HTML5学习笔记之表格标签 HTML5学习笔记之表单标签 HTML5学习笔 ...

  2. Mbatis逆向工程常遇错误

    org.apache.ibatis.exceptions.PersistenceException: ### Error building SqlSession.### The error may e ...

  3. Mysql 查看被锁住的表

    MYSQL  查看被锁住的表 -- 本文章仅用于学习,记录   当你在mysql 执行查询语句的时候,简单的一句查询语句却卡很久,一直转圈圈的时候,这时候你就需要怀疑数据库的哪些进程,哪些事物被锁住 ...

  4. csp-j2019游记

    我一pj蒟蒻这点水平还来写游记? 算了,毕竟是第一次,记录一下吧 noip->csp 话说我跟竞赛是不是天生八字不合啊...... 小学的时候学小奥,等我开始报名比赛,当时似乎所有竞赛都被叫停了 ...

  5. cookie、session 和 token 区别

    1.什么是 cookie cookie 是保存在本地终端的数据.cookie 由服务器生成,发送给浏览器,浏览器把 cookie 以 kv 形式保存到某个目录下的文本文件内,下一次请求同一网站时会把该 ...

  6. CentOS安装boost

    安装其实很简单的: tar zxvf boost_1_59_0.tar.gz cd boost_1_59_0 ./bootstrap.sh --prefix=/usr/local/boost ./b2 ...

  7. Northwestern European Regional Contest 2014 Gym - 101482

    Gym 101482C Cent Savings 简单的dp #include<bits/stdc++.h> #define inf 0x3f3f3f3f #define inf64 0x ...

  8. B. Modulo Sum dp

    https://codeforces.com/contest/577/problem/B 先读懂题意,substring 这个是子串说明不可以跳 subsequence这个是子序列可以跳 这个题目是一 ...

  9. D - 小Z的加油店 线段树+差分+GCD

    D - 小Z的加油店 HYSBZ - 5028   这个题目是一个线段树+差分+GCD 推荐一个差分的博客:https://www.cnblogs.com/cjoierljl/p/8728110.ht ...

  10. 解决使用nlpir分词,遇到License过期问题

    问题:使用pynlpir分词,遇到License过期问题 抛出异常:pynlpir.LicenseError: Your license appears to have expired. Try ru ...