Read configuration information

Source: Internet
Author: User

Configuration of ASP (1): Read configuration information

Referring to the word "configuration", I think most of it. NET developers in mind will immediately emerge two special files, that is we are familiar with the app. Config and Web. config, for many years we have been accustomed to the structure of configuration information defined in these two files. When we get to. NET core, a lot of things that we take for granted change, including the way you define configurations. In general, the new configuration system appears to be more lightweight and more scalable, and its greatest feature is the support for diverse data sources. We can use the memory variables as the configured data source, or we can directly configure the persisted files or even the database.

Since a lot of people have never been in touch with this newly designed configuration system, in order to have a sense of this, we start with a programmatic perspective of it first. The API for configuration involves three objects, namely, configuration, Configurationbuilder, and Configurationprovider, which have corresponding interfaces to represent them. The relationship between the three objects is clear, the configuration object carries the configured information that is used during the programming process, and Configurationprovider is the provider of the original data source for the configuration information. Communication between the two is done by Configurationbuilder, which uses Configurationprovider to extract the source data and convert it to a configuration object.

First, read the configuration in the form of a key-value pair

Although the configuration information in most cases has a structured hierarchical relationship, but the "atomic" configuration items are represented in the simplest "key-value pairs", and the keys and values are strings, we will then demonstrate how to read the configuration in the form of a key-value pair using a simple example. We create a console app for ASP. NET core and add a dependency on the NuGet package for "Microsoft.Extensions.Configuration" in Project.json as follows, The configuration model is implemented in this package.

   1: {
   2: ...   
   3:   "dependencies": {
   4: "     Microsoft.Extensions.Configuration": "1.0.0-rc1-final"
   5:   },
   6:}

Assuming that our application needs to be configured to set the date/time display format, we have defined the following Datetimeformatsettings class, which has four properties that reflect the four display formats of the DateTime object (long Date/time and short Date/time, respectively).

   1:public class Datetimeformatsettings
   2: {
   3: Public     string Longdatepattern {get; set;}
   4: Public     string Longtimepattern {get; set;}
   5: Public     string ShortDatePattern {get; set;}
   6: Public     string Shorttimepattern {get; set;}
   7:     //other Members
   8:}

We want to control the date/time display format represented by the four properties of datetimeformatsettings in the form of configuration, so we define a constructor for it. As shown in the following code fragment, the constructor has an IConfiguration interface type parameter, which formally hosts the configuration object for the related config information. We call the index of the configuration object and specify the key of the corresponding config item to get its value.

   1:public class Datetimeformatsettings
   2: {
   3:     //other Members
   4: Public     datetimeformatsettings (iconfiguration configuration)
   5:     {
   6: This         . Longdatepattern     = configuration["Longdatepattern"];
   7: This         . Longtimepattern     = configuration["Longtimepattern"];
   8: This         . ShortDatePattern    = configuration["ShortDatePattern"];
   9: This         . Shorttimepattern    = configuration["Shorttimepattern"];
  Ten:     }
  11:}

To create a Datetimeformatsettings object that embodies the current configuration, we have to get to the configuration object that hosts the relevant config information. As we said above, the configuration object is created by Configurationbuilder, and the original config information is read by the corresponding configurationprovider. So the correct way to programmatically create a configuration object is to first create a Configurationbuilder object and then add one or more Configurationprovider objects to it. Finally, we use Configurationbuilder to create the configuration objects we need.

In accordance with the above programming pattern, we have written the following program in a console application. We have created an object of type Configurationbuilder, and calling its Add method adds Configurationprovider is an object of type Memoryconfigurationprovider. As the name implies, Memoryconfigurationprovider uses objects in memory to provide the original configuration information, specifically these original configuration information is saved in an element type of keyvaluepair<string, string> In the collection. We eventually call the build method of Configurationbuilder to get the configuration needed to create the Datetimeformatsettings object.

   1:public class Program
   2: {
   3: Public     static void Main (string[] args)
   4:     {
   5:         dictionary<string, string> Source = new Dictionary<string, string>
   6:         {
   7:             ["Longdatepattern"]     = "dddd, MMMM D, yyyy",
   8:             ["Longtimepattern"]     = "H:mm:ss tt",
   9:             ["ShortDatePattern"]    = "m/d/yyyy",
  Ten:             ["Shorttimepattern"]    = "h:mm tt"
  One:         };
  :         iconfiguration configuration = new Configurationbuilder ()
  :                 . ADD (new Memoryconfigurationprovider (source))
  :                 . Build ();
  
  :         datetimeformatsettings settings = new datetimeformatsettings (configuration);
  :         Console.WriteLine ("{0,-16}: {1}", "Longdatepattern", settings. Longdatepattern);
  :         Console.WriteLine ("{0,-16}: {1}", "Longtimepattern", settings. Longtimepattern);
  :         Console.WriteLine ("{0,-16}: {1}", "ShortDatePattern", settings. ShortDatePattern);
  :         Console.WriteLine ("{0,-16}: {1}", "Shorttimepattern", settings. Shorttimepattern);
  :     }
  22:}

To verify the relationship between the Datetimeformatsettings object created by the configuration and the configuration of the original data, we output its four properties to the console. When the program executes, it will produce the output shown below on the console, which shows that it is the true reflection of the configuration we provide.

   1:LONGDATEPATTERN:DDDD, MMMM D, yyyy
   2:LONGTIMEPATTERN:H:MM:SS TT
   3:shortdatepattern:m/d/yyyy
   4:SHORTTIMEPATTERN:H:MM TT

Second, read the structured configuration

Most of the configurations involved in a real project have a structured hierarchy, so the configuration object in the Config model also has such a structure. A structured configuration has a tree hierarchy, and a configuration object represents a node that makes up the configuration tree, which can be represented by a config object that is the root node. Atomic configuration items that are represented as key-value pairs typically exist in a configuration object that is a leaf node, and the configuration of a non-leaf node contains a set of child nodes, and each child node is also a configuration object.

Next we also demonstrate how to define and read a configuration with a hierarchical structure as an example. We still use the previous section of the application scenario, now we need not only to set the date/time format, but also to set the format of other data types, such as the decimal type that represents the currency. For this we define the following Currencydecimalformatsettings class, whose properties digits and symbol represent the decimal place and the currency symbol, respectively. A Currencydecimalformatsettings object is still created using a configuration object that represents configurations.

   1: {
   2: public     int     Digits {get; set;}
   3: Public     string  Symbol {get; set;}
   
   5: Public     currencydecimalformatsettings (iconfiguration configuration)
   6:     {
   7: This         . Digits = Int. Parse (configuration["Digits"]);
   8: This         . Symbol = configuration["symbol"];
   9:     }
  10:}

We have defined another type named Formatsettings to represent formatting for different data types. As shown in the following code snippet, its two properties datetime and currencydecimal represent formatting for date/time and currency numbers, respectively. Formatsettings still has a constructor with a parameter type of IConfiguration interface, and its two properties are initialized in this constructor. It is important to note that the initialization of these two properties takes the "Child configuration section" of the current configuration, which is obtained by invoking the GetSection method by specifying the configuration section name.

   1:public class Formatsettings
   2: {
   3: Public     datetimeformatsettings            DateTime {get; set;}
   4: Public     currencydecimalformatsettings     currencydecimal {get; set;}
   
   6: Public     formatsettings (iconfiguration configuration)
   7:     {
   8: This         . DateTime = new Datetimeformatsettings (configuration. GetSection ("DateTime"));
   9: This         . Currencydecimal = new Currencydecimalformatsettings (configuration. GetSection ("Currencydecimal"));
  Ten:     }
  11:}

In the example we demonstrated above, we provide the original configuration information by using a Memoryconfigurationprovider object. Because the original configuration information is hosted by an element type of keyvaluepair<string, string>, the original configuration does not have a tree-structured hierarchy on the physical storage, So how can it ultimately provide a structured configuration object? It is very simple, although the Memoryconfigurationprovider object can only store configuration information as a simple "data dictionary", but if the path that the configuration object embodies in the config tree is the key, This data dictionary logically actually has a tree structure. In fact, this is what Memoryconfigurationprovider is doing, which is reflected in the program we have shown below.

   1:class Program
   2: {
   3:     static void Main (string[] args)
   4:     {
   5:         dictionary<string, string> Source = new Dictionary<string, string>
   6:         {
   7:             ["Format:DateTime:LongDatePattern"]     = "dddd, MMMM D, yyyy",
   8:             ["Format:DateTime:LongTimePattern"]     = "H:mm:ss tt",
   9:             ["Format:DateTime:ShortDatePattern"]     = "m/d/yyyy",
  Ten:             ["Format:DateTime:ShortTimePattern"]     = "h:mm tt",
  
  :             ["Format:CurrencyDecimal:Digits"]     = "2",
  :             ["Format:CurrencyDecimal:Symbol"]     = "$",
  :         };
  :         iconfiguration configuration = new Configurationbuilder ()
  A:                 . ADD (new Memoryconfigurationprovider (source))
  :                 . Build ();
  
  :         formatsettings settings = new Formatsettings (configuration. GetSection ("Format"));
  :         Console.WriteLine ("DateTime:");
  :         Console.WriteLine ("\t{0,-16}: {1}", "Longdatepattern", settings. Datetime.longdatepattern);
  :         Console.WriteLine ("\t{0,-16}: {1}", "Longtimepattern", settings. Datetime.longtimepattern);
  1:         Console.WriteLine ("\t{0,-16}: {}", "ShortDatePattern", settings. Datetime.shortdatepattern);
  :         Console.WriteLine ("\t{0,-16}: {1}\n", "Shorttimepattern", settings. Datetime.shorttimepattern);
  
  :         Console.WriteLine ("Currencydecimal:");
  :         Console.WriteLine ("\t{0,-16}: {1}", "Digits", settings. Currencydecimal.digits);
  :         Console.WriteLine ("\t{0,-16}: {1}", "Symbol", settings. Currencydecimal.symbol);
  :     }
  30:}

As shown in the code snippet above, the Dictionary object that is used to create the Memoryconfigurationprovider object contains 6 basic configuration items, in order for them to logically have a tree-structured hierarchy, So the key actually embodies the path of the configuration section in the configuration tree where each configuration item is located, and the path is split with a colon (":"). After the program executes, the output shown below will be rendered on the console.

   1:datetime:
   2:         longdatepattern:dddd, MMMM D, yyyy
   3:         longtimepattern:h:mm:ss TT
   4:         shortdatepattern:m/d/yyyy
   5:         shorttimepattern:h:mm TT
   
   7:currencydecimal:
   8:         Digits          : 2
   9:         Symbol          : $

III. binding a structured configuration directly to an object

In the real project development process, we will not directly use the direct read configuration, but are inclined to like the two examples we demonstrate by creating the appropriate type (such as Datetimeformatsettings, Currencydecimalsettings and Formatsettings) to define a set of related configuration options (option), we will define the configuration options (option) for these types called option types. In the example shown above, in order to create these encapsulated configuration objects, we are in the form of manual read configuration, if there are too many defined configuration items, read-only configuration item is a very tedious task.

For an object, if we treat its property as its child node, an object also has a tree-like hierarchical structure similar to the configuration object. If we define the configuration based on the structure of an option type, or the option type is defined in turn based on the configured structure, then the attribute member of option type will have a one by one corresponding relationship with a configuration section. So in principle we can automatically bind configuration information to a specific option object.

ASP. NET core for the configured option model (Optionmodel) helps us implement bindings from configuration to option objects, and then we'll do a simple demonstration of this. The option model is implemented in the "Microsoft.Extensions.OptionModel" NuGet package, except that we need to use the option model in a way that relies on injection, so we need to add an appropriate dependency for the app as follows.

   1: {
   2: ...   
   3:   "dependencies": {
   4: "     Microsoft.Extensions.OptionsModel"        : "1.0.0-rc1-final",
   5: "     Microsoft.Extensions.DependencyInjection"    : "1.0.0-rc1-final"
   6:   },
   7:}

With the option model's automatic binding mechanism, we no longer have to manually read the configuration information, so we remove the formatsettings, datetimeformatsettings, and Currencydecimalsettings constructors, Retains only its property members. In the main method as the entrance to the program, we create the Formatsettings object that represents the formatting in the following way.

   1:class Program
   2: {
   3:     static void Main (string[] args)
   4:     {
   5:         dictionary<string, string> Source = new Dictionary<string, string>
   6:         {
   7:             ["Format:DateTime:LongDatePattern"] = "dddd, MMMM D, yyyy",
   8:             ["Format:DateTime:LongTimePattern"] = "H:mm:ss tt",
   9:             ["Format:DateTime:ShortDatePattern"] = "m/d/yyyy",
  Ten:             ["Format:DateTime:ShortTimePattern"] = "h:mm tt",
  
  :             ["Format:CurrencyDecimal:Digits"] = "2",
  :             ["Format:CurrencyDecimal:Symbol"] = "$",
  :         };
  :         iconfiguration configuration = new Configurationbuilder ()
  A:                 . ADD (new Memoryconfigurationprovider (source))
  :                 . Build ()
  :                 . GetSection ("Format"));
  
  :         ioptions<formatsettings> optionsaccessor = new Servicecollection ()
  A:             . AddOptions ()
  A:             . Configure<formatsettings> (Configuration)
  At:             . Buildserviceprovider ()
  A:             . Getservice<ioptions<formatsettings>> ();
  
  :         formatsettings settings = Optionsaccessor.value;
  
  :         Console.WriteLine ("DateTime:");
  :         Console.WriteLine ("\t{0,-16}: {1}", "Longdatepattern", settings. Datetime.longdatepattern);
  :         Console.WriteLine ("\t{0,-16}: {1}", "Longtimepattern", settings. Datetime.longtimepattern);
  To:         Console.WriteLine ("\t{0,-16}: {1}", "ShortDatePattern", settings. Datetime.shortdatepattern);
  :         Console.WriteLine ("\t{0,-16}: {1}\n", "Shorttimepattern", settings. Datetime.shorttimepattern);
  
  Console.WriteLine:         ("Currencydecimal:");
  :         Console.WriteLine ("\t{0,-16}: {1}", "Digits", settings. Currencydecimal.digits);
  :         Console.WriteLine ("\t{0,-16}: {1}", "Symbol", settings. Currencydecimal.symbol);
  Panax Notoginseng:     }
  38:}

As shown in the code snippet above, we create a Servicecollection object and call the extension method AddOptions registered with the service for the option model. Next we call the Configure method to map the option type formatsettings to the corresponding configuration object. We finally use this Servicecollection object to generate a serviceprovider, and call its GetService method to get an object of type ioptions<formatsettings>, The latter's Value property returns the Formatsettings object that is bound to the associated configuration.

Read configuration information

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.