一、引包
1.Microsoft.Extensions.Configuration
2.Microsoft.Extensions.Configuration.Json
3.Microsoft.Extensions.Configuration.Binder
4.Microsoft.Extensions.DependencyInjection
5.Microsoft.Extensions.Options
二、创建配置文件
创建一个json文件,并且复制到输出目录设置成如果较新复制
{ "data":"21", "db": { "ConnectionString": "链接字符串", "DbType": "mysql" } }
三、配置文件(ConfigurationBuilder类)的基本使用
ConfigurationBuilder configBuilder = new ConfigurationBuilder(); //先加载配置文件 //path=文件路径;optional=true文件不存在不报错,false文件不存在报错;reloadOnChange文件修改了是否重新加载 configBuilder.AddJsonFile(path:"config.json",optional: true, reloadOnChange:true); IConfigurationRoot root = configBuilder.Build(); { var str = root["data"]; Console.WriteLine(str); } { var str = root.GetSection("db:DbType").Value; Console.WriteLine(str); } //说明:索引也可以使用GetSection当中的JsonPath写法,
四、创建实体类
/// <summary> ///配置文件的依赖注入不能直接引用实体类, ///需要使用: ///IOptions<Demo>说明:重启后更改配置 ///IOptionsMonitor<Demo>说明:暂时没明白 ///IOptionsSnapshot<Demo>说明:更改后立即生效 /// </summary> internal class Demo { IOptionsSnapshot<DbSettings> options; public Demo(IOptionsSnapshot<DbSettings> options) { this.options = options; } public void read() { Console.WriteLine("数据库"+options.CurrentValue.DbType); } }
五、结合ServiceCollection读取配置文件。
ConfigurationBuilder configBuilder = new ConfigurationBuilder(); configBuilder.AddJsonFile(path:"config.json",optional: true, reloadOnChange:true); IConfigurationRoot root = configBuilder.Build(); ServiceCollection services = new ServiceCollection();
//实体类绑定配置文件json对象 services.AddOptions().Configure<DbSettings>(r => root.GetSection("db").Bind(r)); services.AddTransient<Demo>(); using(var sp = services.BuildServiceProvider()) { while (true) { using(var p = sp.CreateAsyncScope()) { var demo = p.ServiceProvider.GetService<Demo>(); demo!.read(); } Console.Write("读取成功"); Console.ReadKey(); } }
成功更改。
标签:core,asp,Console,配置文件,Extensions,configBuilder,true,Microsoft From: https://www.cnblogs.com/lzyyyds/p/16834118.html