Under NETCore IConfiguration and IOptions usage

NETCore Web API to create a new project, it will start using IConfiguration and IOptions in Startup.cs, we see how to use.
IConfiguration is used to load configuration values, can be loaded memory key-value pairs, JSON or XML configuration file, we usually used to load the default appsettings.json.

1. 注入 IConfiguration

Startup time to execute, IConfiguration has been injected into the services, and we do not need to add extra injected code, the default is to read appsettings.json file, you can understand in Startup.cs have hidden a code injection similar to the following:

var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); Configuration = builder.Build(); services.AddSingleton<IConfiguration>(Configuration); 

2. 使用 IConfiguration

Let's set about appsettings.json

{
  "test1":"v1", "test2":{ "key1":"v2", "key2":"v3", "key3":4, "key4":true } } 

Incoming IConfiguration in the Controller directly in the constructor


 
image.png

We can see the value in acquiring appsettings.json is simple, if the value of the object is only need to add a colon.
Better way to get an object is IOptions, we are going to see.

3. Fill IOptions

OptionSample first define a class needs to implement IOptions Interface:


 
image.png

Then, inject code is very simple

services.Configure<OptionSample>(Configuration.GetSection("test2")); 

This is equivalent to the following code words

OptionSample sample = new OptionSample(); sample.key1 = Configration["test2:key1"]; sample.key2 = Configration["test2:key2"]; sample.key3 = Configration["test2:key3"]; sample.key4 = Configration["test2:key4"]; services.AddSingle<IOptions<OptionSample>>(sample); 

4. Use IOptions

This same pass parameter in the constructor


 
image.png

We can see in NETCore ubiquitous dependency injection. Source reference Github



Author: voxer
link: https: //www.jianshu.com/p/b9416867e6e6
Source: Jane books
are copyrighted by the author. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/nimorl/p/12570823.html