Configuration and Retrieval in ASP.NET Core

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

ASP.NET Core provides the ConfigurationBuilder object for building configurations. It mainly consists of three steps: configuring the data source -> ConfigurationBuilder -> usage. The data source can come from a dictionary or configuration files.

The data source must either inherit from IConfigurationSource or be read from a configuration file.

1. From Dictionary

First, we store key-value pairs in a dictionary for configuration, such as test = 配置, and then use the ConfigurationBuilder.Add() method to add the data source. The Add method can accept data sources that inherit from IConfigurationSource.

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

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

To avoid frequently using new, we can read the data source from the dictionary using 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

Suppose we create a JSON file in the project's root directory 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 use SetBasePath() to define the path, as shown below:

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

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

Additionally, we can monitor the JSON file for changes, updating automatically when 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 with the following content:

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

When using it, we can use the : symbol to access the next level of child item configurations.

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

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

If you only want to get the LogLevel part of the configuration 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"];

Through the JSON configuration file, we can conveniently build hierarchically structured configurations. If we want to store this in a dictionary, we can use the format "{k1}:{k2}". 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 https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#getsection-getchildren-and-exists

痴者工良

高级程序员劝退师

文章评论