SoFunction
Updated on 2025-03-07

Core reads configuration files

In Core, you can use the ConfigurationBuilder object to build.

It is mainly divided into three parts: Configuration Data Source -> ConfigurationBuilder -> Use.

The data source can be from a dictionary or configuration file.

The data source either inherits the IConfigurationSource or reads from the configuration file.

1, from the dictionary

Let's first use a dictionary to store key-value pairs to set the configuration.test = configuration, then use()Method to add data source,AddMethods can be added to inheritIConfigurationSourcedata source.

MemoryConfigurationSourceInheritedIConfigurationSource, use dictionary as data source.

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

It's not very good to always have new, so you can use the following method to read the data source in the dictionary:

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

2, from the configuration file

If you create a json file in the project root directory, the content is as follows:

{
"test":"Configuration"
}

Then you can read the configuration like this:

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

If the configuration file is not in the root directory, you can useSetBasePath()To define the path, the example is as follows:

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

As shown above, it is very simple to obtain configuration items.config["{KeyName}"]You can getvalue

In addition, you can monitor json files and actively update them when the json file changes.

                ("", 
                    optional: true, 
                    reloadOnChange: true);

3. Hierarchy

The configuration data source can have a hierarchy.

There is a file in Core, with the contents as follows:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "": "Information"
    }
  }
}

Then when we use it, we can use it:Symbols get the configuration of the next layer of child items.

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

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

If you just want to get the json fileLogLevelSome configurations can be usedGetSection()method.

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

            string test = config["Default"];

Through the json configuration file, we can easily build hierarchical configurations. If we want to store them in the dictionary, we can use the form "{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 useGet<>()Method, map configurations to objects.

    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>();

This is all about this article about Core reading configuration files. I hope it will be helpful to everyone's learning and I hope everyone will support me more.