Configuration and Retrieval in ASP.NET Core

2020年6月5日 4点热度 0人点赞 1条评论
内容目录

ASP.NET Core allows the use of the ConfigurationBuilder object for configuration management. The process can be divided into three main steps: configure data sources -> create ConfigurationBuilder -> use the configuration. Data sources can come from a dictionary or configuration files.

Data sources either inherit from IConfigurationSource or read from configuration files.

1. From Dictionary

First, we use a dictionary to store key-value pairs to set up the configuration, with test = 配置. Then, we use the ConfigurationBuilder.Add() method to add the data source. The Add method can append sources that inherit from IConfigurationSource.

MemoryConfigurationSource inherits from IConfigurationSource and uses a dictionary as its data source.

            var dic = new Dictionary<string, string>()
            {
                ["test"] = "配置"
            };
            var config = new ConfigurationBuilder()
                .Add(new MemoryConfigurationSource() { InitialData = dic }).Build();
            string test = config["test"];

Using new repeatedly may feel cumbersome, so we can read the data source from the dictionary with the following method:

            var dic = new Dictionary<string, string>()
            {
                ["test"] = "配置"
            };
            var config = new ConfigurationBuilder()
                .AddInMemoryCollection(dic)
                .Build();
            string test = config["test"];

2. From Configuration File

If we create a JSON file in the root directory of the project with the following content:

{
  "test": "配置"
}

We can read the configuration like this:

            var config = new ConfigurationBuilder()
                .AddJsonFile("test.json")
                .Build();
            string test = config["test"];
            Console.WriteLine(test);

If the configuration file is not in the root directory, we can define the path using SetBasePath(), as shown below:

            var config = new ConfigurationBuilder()
                .SetBasePath("E:\\test\\aaa")
                .AddJsonFile("test.json")
                .Build();

As seen above, accessing configuration items is very straightforward; config["{KeyName}"] retrieves the corresponding value.

Additionally, we can monitor the JSON file, allowing for updates whenever the file changes.

                config.AddJsonFile("appsettings.json", 
                    optional: true, 
                    reloadOnChange: true);

3. Hierarchical Structure

Configuration data sources can have a hierarchical structure. In ASP.NET Core, there is typically an appsettings.json file, which contains the following:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

When using it, we can retrieve configuration for the next level of child items using the : symbol.

            var config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .Build();

            string test = config["Logging:LogLevel:Default"];

If you only want to retrieve the configuration under LogLevel from the JSON file, you can use the GetSection() method.

            var config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .Build()
                .GetSection("Logging:LogLevel");

            string test = config["Default"];

Using a JSON configuration file, we can conveniently build hierarchical configurations. If you want to store these in a dictionary, you can use the "{k1}:{k2}" format, for example:

            var dic = new Dictionary<string, string>()
            {
                ["testParent:Child1"] = "6",
                ["testParent:Child2"] = "666"
            };
            var config = new ConfigurationBuilder()
                .AddInMemoryCollection(dic)
                .Build().GetSection("testParent");

            string test = config["Child1"];

4. Mapping

We can use the Get<>() method to map the configuration to an object.

    public class TestOptions
    {
        public string A { get; set; }
        public string B { get; set; }
        public string C { get; set; }
    }
            var dic = new Dictionary<string, string>()
            {
                ["A"] = "6",
                ["B"] = "66",
                ["C"] = "666"
            };
            TestOptions config = new ConfigurationBuilder()
                .AddInMemoryCollection(dic)
                .Build().Get<TestOptions>();

You can also refer to Microsoft Documentation for more information.

痴者工良

高级程序员劝退师

文章评论