本文介绍了在NET CORE项目中非controller和service如何动态全局获取appsetting.json配置的方法,包括注入、文件监听、工具类创建ConfigurationBuilder以及使用IOptionsMonitor。通过创建配置文件对应的实体类,可以在配置文件改变时实时获取更新的设置,而无需重启项目。 摘要由CSDN通过智能技术生成

最近在写NET CORE的项目,在非controller和service里面需要用到appsetting.json文件里面的一些配置,查资料大概有几种思路:

  • 注入,然后config.GetSection("xxx")获取section。
  • 写一个文件监听fileWatch,去监听appsetting.json的变化,读取key-value。
  • 使用工具类再创建一遍ConfigurationBuilder: new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true)
  • 使用IOptions,创建对应的实体类,然后获取实体类。

查资料的时候发现了一个IOptionsMonitor,这个可以监听到文件的变化,结合IOptionsMonitor,我写了一个工具类,具体使用办法如下:

(1)创建appsetting.json对应的实体类文件,属性的名字要与配置文件里面的一一对应。

// 实体类public class AllSetting{        /         / 数据库配置        /         public ConnectionSetting ConnectionStrings { get; set; }        /         / 日志模块        /         public LoggingSetting Logging { get; set; }        /         / AllowedHosts         /         public string AllowedHosts { get; set; }}// 对应的配置文件{    "ConnectionStrings": {        "DefaultConnection": "xxxx"        //"PgSqlConnection": "xxxx",        //"MySqlConnection": "xxxx",        //"OracleConnection": "xxxx"    },    "Logging": {        "LogLevel": {            "Default": "Warning"        }    },    "AllowedHosts": "*",    "Gateway": {        "Uri": "xxxx"    }}

(2)编写工具类AppsettingsUtility。

///     /// 全局获取app的设置工具类    ///     public class AppsettingsUtility    {        ///         /// log4net        ///         private readonly ILog log;        ///         /// serviceProvider        ///         private static ServiceProvider serviceProvider;        ///         /// _services        ///         private static IServiceCollection _services;        ///         /// _configuration        ///         private static IConfiguration _configuration;        ///         /// 初始化工具类        ///         ///         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());            }        }        ///         /// 获取IOptionsMonitor        ///         /// 泛型        /// IOptionsMonitor        public static IOptionsMonitor GetMonitor()        {            if (serviceProvider == null)            {                throw new NullReferenceException("获取失败,ServiceProvider为空");            }            if (typeof(T) != typeof(AllSetting))            {                // TODO: 要限定传递的参数值或者每个setting都注册一遍            }            return serviceProvider.GetRequiredService>();        }        ///         /// 获取单个的设置实体        ///         /// 泛型        /// T        public static T GetSettingsModel()        {            if (serviceProvider == null)            {                throw new NullReferenceException("获取失败,ServiceProvider为空");            }            if (typeof(T) != typeof(AllSetting))            {                // TODO: 要限定传递的参数值或者每个setting都注册一遍            }            return serviceProvider.GetRequiredService>().CurrentValue;        }        ///         /// 通过key获取设置        ///         /// key        /// 设置内容        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(Configuration);// 初始化工具类new AppsettingsUtility(services,Configuration);

(4)使用。

var aa = AppsettingsUtility.GetMonitor().CurrentValue;var bb = AppsettingsUtility.GetSettingsModel();var bb = AppsettingsUtility.GetSetting("Appsetting:xxx");

如果把配置文件改变了,再调用获取设置的时候,设置的值会更新,项目不用重启。这样做对性能的影响没有测试。

如果我这边的思路有什么错误的话,还望批评指出。

画了一个界面,通过界面输入数据, 获取 输入的数据,添加到数据库。 前面已经把 JTextField 、JComboBox组件写好了,以上面的界面为例,通过在界面输入,然后收集输入数据,收集数据如下: // 获取 JTextField 组件里的字符串数据,把字符串转换成int 类型 int empno = Integer.valueOf(empNoTf.getText()); String ename = empNameTf.getText(); String job = jobTf.getText();
" App Set ting ": {     "connString": "Database=student_db;Data Source=localhost;User Id=root;Password=root;Char Set =utf8;port=3306" 2,建立存储 配置和 读取 配置的类  public cla... 最近在研究把asp.net程序移植到linux上,正好.net core 出来了,就进行了学习。 移植代码基本顺利,但是发现.net core 中没有 Configuration Manager,无法读写配置文件,单独写个xml之类的嫌麻烦,就谷歌了下,发现了个方法,遂记录如下,方便以后查找: 配置文件结构 public class Demo Set ting s public string MainDomain { get; set ; } public string SiteName { get; set ; } app set ting s. json 中显示效果 app set tin 你要明白,任何问题都不是孤立存在的,一定有人曾经遇到过,并且已经有更好的解决办法了,只是我还不知道。我不应该在黑暗中独自前行,去重新发明轮子,也许我的顿悟,只是别人的基本功!我应该要站在巨人的肩膀上,学习更成熟的经验和方法,然后再来解决这个问题 08-11
对于ASP.NET Core 的新的配置方式做个学习笔记,和之前版本的ASP.NET有很大的区别了,之前是依赖于System. Configuration 和XML配置文件web.config,新的配置系统支持多种格式的配置文件。下面就以 json 配置一波 json 配置文件 using Microsoft.Extensions. Configuration ;//引用 public class ValuesController : ControllerBase privat.
1、在Startup.cs文件中注入,ConfigureServices方法  services.Configure<MyConfig>( Configuration .GetSection("MyConfig")); App Set ting . json 文件 "MyConfig": { "ResVersion": "1.0.2 Beta" 自定义...
.Net Core 读取 配置文件 app set ting . json 中的配置项 1、 app set ting s. json 添加配置项 2、新建一个类,对应配置项名称,例如WxCommon下的 3、将配置项注入到启动类Startup.cs 4、配置项需要依赖注入后调用
"Default": "Information", "Microsoft": "Warning", "Microsoft.Hos ting .Lifetime": "Information" "ConnectionStrings": { "YX": "144@qq.com" "AllowedHosts": "*", "ServiceUrl.
文章目录一、创建项目二、配置文件 读取 方式一start.up中输出配置文件信息控制器中输出配置文件信息三、配置文件 读取 方式二四、源码 一、创建项目 1、创建一个NET Core 5.0的Web API项目。 2、 app set ting . json 中的 内容 如下: "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hos ting .Lifetime