. NET Core Development Logs--configuration

Source: Internet
Author: User

Developers familiar with ASP. Web. config files must not be unfamiliar. In an ASP. NET environment, in order to add configuration parameters, it is usually done in this file. One of the most common is appsettings and connectionstrings two items. To get configuration information from the file in your code, ConfigurationManager is an essential assembly to introduce.

However, in the ASP. NET core era, the way the storage and read configurations changed.

If you know something about an ASP. NET core project, you should see the Appsettings.json file. This explains how the configuration information is read in ASP. NET core from the JSON file configuration method.

Suppose there are pre-set Appsettings.json files:

{  "option1": "value1_from_json",  "option2": 2,  "subsection": {    "suboption1": "subvalue1_from_json"  },  "wizards": [    {      "Name": "Gandalf",      "Age": "1000"    },    {      "Name": "Harry",      "Age": "17"    }  ]}

Reading in code can be done as follows:

 public class program{public static iconfiguration Configuration {get; set;} public static void Main (string[] args = null) {var builder = new Configurationbuilder (). Setbasepath (Directory.GetCurrentDirectory ()). Addjsonfile ("Appsettings.json"); Configuration = Builder. Build (); Console.WriteLine ($ "option1 = {configuration[" Option1 "]}"); Console.WriteLine ($ "option2 = {configuration[" option2 "]}"); Console.WriteLine ($ "Suboption1 = {configuration[" Subsection:suboption1 "]}"); Console.WriteLine (); Console.WriteLine ("Wizards:"); Console.Write ($ "{configuration[" Wizards:0:name "]},"); Console.WriteLine ($ "Age {configuration[" wizards:0:age "]}"); Console.Write ($ "{configuration[" Wizards:1:name "]},"); Console.WriteLine ($ "Age {configuration[" wizards:1:age "]}"); Console.WriteLine (); Console.WriteLine ("Press a key ..."); Console.readkey (); }}

First, instantiate a Configurationbuilder object, and then set the base path.

The Setbasepath operation is actually setting the value of Fileprovider in the Configurationbuilder's property dictionary.

public static IConfigurationBuilder SetBasePath(this IConfigurationBuilder builder, string basePath){    ...        return builder.SetFileProvider(new PhysicalFileProvider(basePath));}public static IConfigurationBuilder SetFileProvider(this IConfigurationBuilder builder, IFileProvider fileProvider){    ...    builder.Properties[FileProviderKey] = fileProvider ?? throw new ArgumentNullException(nameof(fileProvider));    return builder;}

Then add the JSON file.

public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange){    ...    return builder.AddJsonFile(s =>    {        s.FileProvider = provider;        s.Path = path;        s.Optional = optional;        s.ReloadOnChange = reloadOnChange;        s.ResolveFileProvider();    });}public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, Action<JsonConfigurationSource> configureSource)    => builder.Add(configureSource);

A Jsonconfigurationsource object is added to the Configurationbuilder.

Finally, by executing the build method of Configurationbuilder, you can get the configuration object that holds the config information.

To summarize the code in the example, the operation to get the configuration information is actually divided into two steps:

    1. Creating a Configuration Object
    2. Key values get information from the configuration object

The steps to generate a configuration object must have at least three basic links.

    1. Generating Configurationbuilder objects
    2. Add Configurationsource Object
    3. Creating a Configuration Object

Looking at the code that creates the configuration object, you will find that the Configurationprovider object created in Configurationsource is actually used internally.

public IConfigurationRoot Build(){    var providers = new List<IConfigurationProvider>();    foreach (var source in Sources)    {        var provider = source.Build(this);        providers.Add(provider);    }    return new ConfigurationRoot(providers);}

Looking at the Iconfiguratonsource interface, there is only one build method.

public interface IConfigurationSource{    IConfigurationProvider Build(IConfigurationBuilder builder);}

The resulting configuration object, known as Configurationroot, contains all the Configurationprovider, which are provided by these configurationprovider.

Tracing to the construction method of the Configurationroot type, sure enough, is loaded on all configurationprovider when it generates the object.

public ConfigurationRoot(IList<IConfigurationProvider> providers){    ...    _providers = providers;    foreach (var p in providers)    {        p.Load();        ChangeToken.OnChange(() => p.GetReloadToken(), () => RaiseChanged());    }}

For example in Jsonconfigurationprovider:

public override void Load(Stream stream){    try    {        Data = JsonConfigurationFileParser.Parse(stream);    }    ...}

Through the JSON parser, the configuration information of the JSON file is read into the Configurationprovider Data property. This property is used to save all configuration information.

  /// <summary>  /// The configuration key value pairs for this provider.  /// </summary>  protected IDictionary<string, string> Data { get; set; }

With the Configurationroot object, it's easy to get the configuration information. Iterate through each configurationprovider to get the first data that matches the key value.

public string this[string key]{    get    {        foreach (var provider in _providers.Reverse())        {            string value;            if (provider.TryGet(key, out value))            {                return value;            }        }        return null;    }    ...}

The Configurationprovider object gets the configured value from the Data property.

public virtual bool TryGet(string key, out string value)    => Data.TryGetValue(key, out value);

This can be seen in the initial example Configuration["wizards:0:Name"] because, when the load file is stored, it is used as a : delimiter for the key value of the nested object.

You can also write in a different way, binding the configuration information to an object.

Define the object type first:

public class AppSettings{    public string Option1 { get; set; }    public int Option2 { get; set; }    public Subsection Subsection { get; set; }    public IList<Wizards> Wizards { get; set; }}public class Subsection{    public string Suboption1 { get; set; }}public class Wizards{    public string Name { get; set; }    public string Age { get; set; }}

Re-bound objects:

static void Main(string[] args){    var builder = new ConfigurationBuilder()        .SetBasePath(Directory.GetCurrentDirectory())        .AddJsonFile("appsettings.json");    Configuration = builder.Build();    var appConfig = new AppSettings();    Configuration.Bind(appConfig);    Console.WriteLine($"option1 = {appConfig.Option1}");    Console.WriteLine($"option2 = {appConfig.Option2}");    Console.WriteLine(        $"suboption1 = {appConfig.Subsection.Suboption1}");    Console.WriteLine();    Console.WriteLine("Wizards:");    Console.Write($"{appConfig.Wizards[0].Name}, ");    Console.WriteLine($"age {appConfig.Wizards[0].Age}");    Console.Write($"{appConfig.Wizards[1].Name}, ");    Console.WriteLine($"age {appConfig.Wizards[1].Age}");    Console.WriteLine();    Console.WriteLine("Press a key...");    Console.ReadKey();}

The notation becomes a common method of object invocation properties, but the result is the same.

In addition to storing configuration information in JSON files, ASP. NET core also supports INI and XML files. Of course, when you have other types of files, you can also IConfigurationSource load a configuration file by implementing an interface and inheriting ConfigurationProvider the class to build a custom Configrationprovider object.

The ASP. NET core also provides a lot of other ways than documents.

    • Command line, Addcommandline
    • Environment variables, addenvironmentvariables
    • Memory, Addinmemorycollection
    • User Confidential, Addusersecrets
    • Azure Key Vault,addazurekeyvault

The method of choosing which storage and reading configuration is based on the actual scenario, and the ASP. NET core has opened the portal to the configuration, and any access method is theoretically feasible. In practice, developers are required to try and explore them.

. NET Core Development Logs--configuration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.