|
|
目录
8 T8 g+ D6 e8 @
! k9 N& h6 I2 J% H( K2 w
( I2 g) r) S5 ]- 添加其他配置文件
, E0 i0 k: U7 c _, O - 源码解读:6 z6 o j0 l! }
- 读取层级配置项
$ ~2 j1 H4 L5 Y5 R5 L5 k- [ - 选项模式获取配置项" l% [0 ] K0 K# w7 \; ^5 E
- 命名选项的使用
; s4 [4 R- Z! o4 C+ j2 F1 Q4 I 不管是.net还是.netcore项目,我们都少不了要读取配置文件,在.net中项目,配置一般就存放在web.config中,但是在.netcore中我们新建的项目根本就看不到web.config,取而代之的是appsetting.json。
/ f# R" v: e) y2 m. |新建一个webapi项目,可以在startup中看到一个IConfiguration,通过框架自带的IOC使用构造函数进行实例化,在IConfiguration中我们发现直接就可以读取到appsetting.json中的配置项了,如果在控制器中需要读取配置,也是直接通过构造! v9 v- y& I; n- Q
函数就可以实例化IConfiguration对象进行配置的读取。下面我们试一下运行的效果,在appsetting.json添加一个配置项,在action中可以进行访问。
2 R1 b$ r5 W: Q8 }% X& a9 w) W% T/ H: F
; ^+ g. a- T6 ~# t% n
添加其他配置文件* M$ j) E/ [# b5 l* {5 r
5 j+ B, w- [5 J+ K# S3 Q) l那我们的配置项是不是只能写在appsetting.json中呢?当然不是,下面我们看看如何添加其他的文件到配置项中,根据官网教程,我们可以使用ConfigureAppConfiguration实现。
1 y: c# d* l( h! P8 C首先我们在项目的根目录新建一个config.json,然后在其中随意添加几个配置,然后在program.cs中添加高亮显示的部分,这样很简单的就将我们新增的json文件中的配置加进来了,然后在程序中就可以使用IConfiguration进行访问config.json中的配置项了。- public class Program{ public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration(configure => { configure.AddJsonFile("config.json"); //无法热修改 }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); });}
复制代码 但是这个无法在配置项修改后读取到最新的数据,我们可以调用重载方法configure.AddJsonFile("config.json",true,reloadOnChange:true)实现热更新。
% D3 L, e# c5 ]5 U9 O除了添加json文件外,我们还可以使用AddXmlFile添加xml文件,使用AddInMemoryCollection添加内存配置- public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((context,configure) => { Dictionary memoryConfig = new Dictionary(); memoryConfig.Add("memoryKey1", "m1"); memoryConfig.Add("memoryKey2", "m2"); configure.AddInMemoryCollection(memoryConfig); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); });
复制代码 源码解读:/ J# v5 `( H& Q1 d' G
$ N2 Z! C5 H' }0 o# q! {在自动生成的项目中,我们没有配置过如何获取配置文件,那.netcore框架是怎么知道要appsetting.json配置文件的呢?我们通过查看源码我们就可以明白其中的道理。- Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); });//CreateDefaultBuilder源码public static IHostBuilder CreateDefaultBuilder(string[] args){ var builder = new HostBuilder(); builder.UseContentRoot(Directory.GetCurrentDirectory()); builder.ConfigureHostConfiguration(config => { config.AddEnvironmentVariables(prefix: "DOTNET_"); if (args != null) { config.AddCommandLine(args); } }); builder.ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName)) { var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName)); if (appAssembly != null) { config.AddUserSecrets(appAssembly, optional: true); } } config.AddEnvironmentVariables(); if (args != null) { config.AddCommandLine(args); } }); .... return builder;}
复制代码 怎么样?是不是很有意思,在源码中我们看到在Program中构建host的时候就会调用ConfigureAppConfiguration对应用进行配置,会读取appsetting.json文件,并且会根据环境变量加载不同环境的appsetting,同时还可以看到应用不仅添加了
) }, V0 ]6 L! g+ N- J! S( Pappsetting的配置,而且添加了从环境变量、命令行传入参数的支持,对于AddUserSecrets支持读取用户机密文件中的配置,这个在存储用户机密配置的时候会用到。
, _! u% n( r0 S3 k/ [( _" l% d那为什么我们可以通过再次调用ConfigureAppConfiguration去追加配置信息,而不是覆盖呢?我们同样可以在源码里面找到答案。- public static void Main(string[] args){ CreateHostBuilder(args).Build().Run();}//以下为部分源码private List _configureAppConfigActions = new List();private IConfiguration _appConfiguration;public IHostBuilder ConfigureAppConfiguration(Action configureDelegate){ _configureAppConfigActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate))); return this;}public IHost Build(){ ... BuildAppConfiguration(); ...}private void BuildAppConfiguration(){ var configBuilder = new ConfigurationBuilder() .SetBasePath(_hostingEnvironment.ContentRootPath) .AddConfiguration(_hostConfiguration, shouldDisposeConfiguration: true); foreach (var buildAction in _configureAppConfigActions) { buildAction(_hostBuilderContext, configBuilder); } _appConfiguration = configBuilder.Build(); _hostBuilderContext.Configuration = _appConfiguration;}
复制代码 框架声明了一个List,我们每次调用ConfigureAppConfiguration都是往这个集合中添加元素,等到Main函数调用Build的时候会触发ConfigurationBuilder,将集合中的所有元素进行循环追加
! g; |, o9 f3 f# D+ h" J到ConfigurationBuilder,最后就形成了我们使用的IConfiguration,这样一看对于.netcore中IConfiguration是怎么来的就很清楚了。; C* X4 j1 q! k& ]- |# ~
+ f6 _4 p* [% \
读取层级配置项8 p9 v( l' I q
9 @0 y. Z) e$ k
如果需要读取配置文件中某个层级的配置应该怎么做呢?也很简单,使用IConfiguration["key:childKey..."]
, a& m3 D1 ]- l1 w3 e$ t4 n X比如有这样一段配置:- "config_key2": { "config_key2_1": "config_key2_1", "config_key2_2": "config_key2_2" }
复制代码 可以使用IConfiguration["config_key2:config_key2_1"]来获取到config_key2_1的配置项,如果config_key2_1下还有子配置项childkey,依然可以继续使用:childkey来获取* j: @1 z' x: e) f& b+ J
- ?0 X D7 u+ r# U7 h4 S. I选项模式获取配置项
~4 A9 L4 V! ]3 B* f
S( w3 N' r5 |; T( Z选项模式使用类来提供对相关配置节的强类型访问,将配置文件中的配置项转化为POCO模型,可为开发人员编写代码提供更好的便利和易读性
1 K% x9 P, o: K b; f# z7 M我们添加这样一段配置:- "Student": { "Sno": "SNO", "Sname": "SNAME", "Sage": 18, "ID": "001" }
复制代码 接下来我们定义一个Student的Model类- public class Student{ private string _id; public const string Name = "Student"; private string ID { get; set; } public string Sno { get; set; } public string Sname { get; set; } public int Sage { get; set; }}
复制代码 可以使用多种方式来进行绑定:
) z) S! a$ v. @8 w4 T: [9 w1、使用Bind方式绑定- Student student = new Student();_configuration.GetSection(Student.Name).Bind(student);
复制代码 2、使用Get方式绑定- var student1 = _configuration.GetSection(Student.Name).Get(binderOptions=> { binderOptions.BindNonPublicProperties = true;});
复制代码 Get方式和Bind方式都支持添加一个Action的重载,通过这个我们配置绑定时的一些配置,比如非公共属性是否绑定(默认是不绑定的),但是Get比BInd使用稍微方便一些,如果需要绑定集合也是一样的道理,将Student! r! ]1 d2 f7 c# }* L, I0 ~
替换成List。9 t1 `0 f# J( ] Z7 D4 Z' F
3、全局方式绑定
! |+ T& ~7 i R7 _7 r前两种方式只能在局部生效,要想做一次配置绑定,任何地方都生效可用,我们可以使用全局绑定的方式,全局绑定在Startup.cs中定义- services.Configure(Configuration.GetSection(Student.Name));
复制代码 此方式会使用选项模式进行配置绑定,并且会注入到IOC中,在需要使用的地方可以在构造函数中进行实例化- private readonly ILogger _logger;private readonly IConfiguration _configuration;private readonly Student _student;public WeatherForecastController(ILogger logger, IConfiguration configuration, IOptions student){ _logger = logger; _configuration = configuration; _student = student.Value;}
复制代码 命名选项的使用( J0 W0 c" `/ a' q
$ U" W5 s6 r7 s3 I! w2 V1 S对于不同的配置节,包含的配置项一样时,我们在使用选项绑定的时候无需定义和注入两个类,可以在绑定时指定名称,比如下面的配置:- "Root": { "child1": { "child_1": "child1_1", "child_2": "child1_2" }, "child2": { "child_1": "child2_1", "child_2": "child2_2" }}public class Root{ public string child_1{get;set;} public string child_2{get;set;}}services.Configure("Child1",Configuration.GetSection("Root:child1"));services.Configure("Child2", Configuration.GetSection("Root:child2"));private readonly ILogger _logger;private readonly IConfiguration _configuration;private readonly Student _student;private readonly Root _child1;private readonly Root _child2;public WeatherForecastController(ILogger logger, IConfiguration configuration, IOptions student,IOptionsSnapshot root){ _logger = logger; _configuration = configuration; _student = student.Value; _child1 = root.Get("Child1"); _child2 = root.Get("Child2");}
复制代码 到此这篇关于浅析.netcore中的Configuration具体使用的文章就介绍到这了,更多相关.net core Configuration内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
+ A: e! z/ a8 a9 J, _
/ A1 H3 H$ {! ^& x来源:http://www.jb51.net/article/232944.htm: d( D- Z' v8 H7 l: P4 ?
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?立即注册
×
|