Use of configuration files

Posted by ukalpa on Mon, 24 Jan 2022 15:19:26 +0100

1. How to add and read configuration file information

The configuration of a project can be written in a file, memory or database. Default configuration file Appsettings json, which is json format data (of course, it can also be INI and XML).
In order not to affect this project, we set up a test project (AppingSettingReadDemo), also called Net Core MVC project.

1. How to add configuration information (write it into the original appsettings.json file)

,
  "option1": "value1",//Simplest key - value pair format
"option2": {
      "suboption2": {
          "subkey1": "subvalue1",
          "subkey2": "subvalue2"
     }
  },  "database": { //Key - object format
    "Server": "IP address:port",
    "Name": "DBTest",
    "UId": "sa",
    "Password": "123456"
  },
  "students": [//Array format
    {
      "Name": "Zhang San",
      "Age": "20"
    },
    {
      "Name": "Li Si",
      "Age": "21"
    }
  ]

2. How to read configuration information

IConfiguration: it is an interface type at the bottom of the configuration file. To obtain configuration information, you need to use this type of object.
(1) Weak type read mode
Switch to HomeController.
How do I get the IConfiguration object—— Dependency injection, through the construction method dependency injection.
How can objects be injected through construction methods?? This is because Net Core has built-in dependency injection. Here we only tell that the configuration is IConfiguration type, then Net Core built-in DI will automatically call the construction method of IConfiguration implementation class to generate instance object configuration.
DI -- responsible for instantiating objects in the application and establishing dependencies between these objects; Maintain the lifecycle between objects.

private IConfiguration Configuration;
        //Inject Configuration object through constructor
        public HomeController(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IActionResult Index()//This place cannot have IConfiguration configuration parameter
        {
            string str1 = Configuration["option1"];
            string str2 = Configuration["database:Name"];
            string str3 = Configuration["option2:suboption2:subkey2"];
            string str4Name = Configuration["students:0:Name"];//Read the array, where 0 represents the first item of the array
            string str4Age = Configuration["students:0:Age"];
            string str5Name = Configuration["students:1:Name"];//Read the array, where 1 represents the second item of the array
            ViewBag.Value1 = str1;
            ViewBag.Value2 = str2;
            ViewBag.Value3 = str3;
            ViewBag.Name1 = str4Name;
            ViewBag.Age1 = str4Age;
            ViewBag.Name2 = str5Name;
            return View();
        }

Front end index cshtml

@{
    ViewData["Title"] = "Home Page";
}
@ViewBag.Value1
@ViewBag.Value2
@ViewBag.Value3
@ViewBag.Name1
@ViewBag.Age1
@ViewBag.Name2
<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>


If the Chinese code is garbled, the solution is to appsetting the configuration file JSON is saved in UTF-8 again. The specific operations are as follows:
Select appsetting Save JSON file | file | appsetting as, and the following dialog box will pop up. Click Save code to open the dialog box and select UTF-8 code, as shown in the following figure. Click OK to save.


(2) Strongly typed configuration
Suppose you want to get the configuration information of the previous database section.
Step 1: create a configuration mapping class (first create a Configs folder), and then create a class, such as database CS, the attribute in the definition class corresponds to the key of the configuration section.

Step 2: inject the service (Database.cs class). At startup In CS, the Database class is associated with the databse configuration section in the configuration file

public void ConfigureServices(IServiceCollection services)
        {
      
            //Map the database configuration section in the configuration file to the database class     
            services.Configure<Database>(Configuration.GetSection("database"));
}

The source code can be seen in startup In CS, Configuration is also injected through the construction method.

Step 3: how to use the strongly typed configuration method—— Inject IOptions type objects, also through the constructor

private IConfiguration Configuration;
        private IOptions<Database> _database;
        //Inject Configuration object through constructor
        public HomeController(IConfiguration configuration, IOptions<Database> database)
        {
            Configuration = configuration;
            _database = database;
        }
public IActionResult Index()//This place cannot have IConfiguration configuration parameter
        {
         
            Database db = _database.Value;//Get the Database instance object by injecting the Value attribute of the object
            ViewBag.database= $"server:{db.Server},name:{db.Name}";//Then you can get its property value by mapping the instance object of the Database class. The placeholder is used here, and the $symbol in front cannot be less
          
            return View();
        }

Consider the following questions:
1. Will the program automatically load the new configuration if the configuration file changes during the program running?
Not at present. Because the IOptions type object is in singleton mode, that is, once the program runs, the instantiated object will be unique.
Change IOptions to IOptions snapshot type (the two yellow shading above need to be modified). It belongs to a Scoped service, and the configuration data will be reloaded for each request (so the configuration file information will be read every time).
Test: just modify the configuration file appsetting The information in JSON, such as modifying the port number and refreshing the next page, will see the changed result - ok
2. The configuration file will be re read every time it is loaded, even if there is no change, which will lead to useless operations. Can it be loaded only when the configuration file is changed?
Change ioptions snapshot to ioptions monitor type, which can automatically monitor the changes of configuration files and automatically load the latest configuration.
At this time_ database. Replace value with_ database.CurrentValue; Because the value attribute does not exist at this time.

Topics: C# JSON