. Net Core Configuration files

Source: Internet
Author: User

How to manage configuration files under. Net Core Preface

According to the issues, System.Configuration no longer exists in. NET Core, Instead, it is provided by a series of Microsoft.Extensions.Cnfiguration.XXX libraries, and the corresponding open source addresses are click here.

Judging from the current open source code, the following class libraries are available under. NET Core:

Microsoft.Extensions.Configuration.Abstractions: Basic Interface

Microsoft.Extensions.Configuration: Implementing the underlying interface above

Microsoft.Extensions.Configuration.FileProviderExtensions: provides overloaded configuration extensions

Microsoft.Extensions.Configuration.Binder: Provides conversion to entity functionality

Microsoft.Extensions.Configuration.FileExtensions: Provides the configuration file root path extension

Here's how to provide support for:

Microsoft.Extensions.Configuration.CommandLine: command-line arguments

Microsoft.Extensions.Configuration.EnvironmentVariables: Environment variables

Microsoft.Extensions.Configuration.Ini:Ini format

Microsoft.Extensions.Configuration.Json:Json format

MICROSOFT.EXTENSIONS.CONFIGURATION.XML:XML format

By the number of class libraries above we can see that we will not need to load more libraries in the future, as long as we can load on demand, we can also look at the new configuration to provide more support for the format, of course, we can also expand to provide more formats to support. Below we begin to enter the text, from beginning to end to learn these 5 kinds of supported configuration formats.

Note: VS2015 development tools are required

Second, the text

First we need to create an empty solution called "coreclrconfiguration", which will demonstrate the following sections in this solution. If the reader is interested in only one of these parts, you can directly scroll to the corresponding content, each section is independent of each other without a corresponding relationship.

What kind of project template should be created as shown:

A CommandLine (Command line arguments)

Add the following dependencies in the new project (named "Commandlinecfg") in Project.json (the specific version should be determined by the reader according to the actual situation):

"Microsoft.Extensions.Configuration.CommandLine": "1.0.0-rc1-final",

"Microsoft.Extensions.Configuration.Binder": "1.0.0-rc1-final"

It is important to note that the dependent library is a global dependent library, not a dependent library under dnx451 or DNXCORE50.

Note: You will need to right-click the "Reference", "restore Package" after the Project.json has specified the dependent library, and the later sections are no longer elaborated.

First, let's start with a simple example that reads the value of a parameter. First open the Program.cs file in which you write the following program:

1 public static void Main (string[] args) 2 {3         var cmdlineconfig = new Commandlineconfigurationprovider (args); 4         C Mdlineconfig.load (); 5  6         string value1 = null, 7        cmdlineconfig.tryget ("Key1", out value1); 8  9         Console.WriteLine ($ " Key1={value1} ");         Console.readkey (); 12}

Here we can see the name "commandlineconfigurationprovider", and later we will provide support for other formats in "Xxxconfigurationprovider "is named, and the base class is"configurationprovider". After the simple introduction, we need to start running the program, we first open the properties of the project, enter some test command line parameters:

Of course, we're just using one of the supported formats, and the other supported formats are:

-key1=value1

--key1=value1

/key1=value1

--key1 Value1

If the reader, after repeating the "/key1 Value2" in the application parameter, will only take the last set value and is not case-sensitive.

Note: If the command-line argument passes the key only and does not pass value then the FormatException exception is thrown at load.

Similar to our usual ORM, for external command line incoming parameters, key we can actually do the projection, the corresponding key is changed to our desired key. For example the above "Key1" we can be changed to "Key2". To do this, you only need to use the second parameter when creating Commandlineconfigurationprovider, for example we will change "Key1" to "Key2":

public static void Main (string[] args) {       dictionary<string, string> defaults = new Dictionary<string, string >       {                "--key1", "Key2"}        };        var cmdlineconfig = new Commandlineconfigurationprovider (args, defaults);        Cmdlineconfig.load ();        string value1 = null;        Cmdlineconfig.tryget ("Key2", out value1);        Console.WriteLine ($ "key1&key2={value1}");                    Console.readkey ();}

Where we can see that the key in the defaults dictionary must be "--" or "-" or else it will throw a ArgumentException exception when the constructor is called. Finally, we can see that the value is obtained by using the name of the key after we have projected it instead of "Key1".

In addition to the above-mentioned way to get the value, but also provides a common model binding, the ability to convert other formats to Poco, so that we can be more rapid development, the following author will be described in two ways, the first is to use our currently created provider to bind, Where Poco is as follows:

public class commandlineargs{Public    string Key1 {get; set;}}

The main method is implemented as follows:

var cmdlineconfig = new Commandlineconfigurationprovider (args); var builder = new Configurationbuilder (); builder. ADD (cmdlineconfig); var item = Builder. Build (). Get<commandlineargs> (); Console.WriteLine ($ "key1&key2={item. Key1} ");

Where configurationbuilder can manage multiple provider, for example, we develop a system where you can add command lines, JSON files, INI files, and XML files to manage them. If we call the builder method, then we can use its return value to get the value we want uniformly, and internally we will try to get the value we need from these provider if there is a value to return immediately, and the model binding is added by extending it. Specifically, the following methods are expanded:

public static class configurationbinder{public        static void Bind (this iconfiguration configuration, object instance) ;        public static Object Get (this iconfiguration configuration, type type);        public static Object Get (this iconfiguration configuration, type type, string key);        public static T-get<t> (this iconfiguration configuration);        public static T-get<t> (this iconfiguration configuration, T defaultvalue);        public static T-get<t> (This iconfiguration configuration, string key);        public static T-get<t> (This iconfiguration configuration, string key, T defaultvalue);}

In fact, now Microsoft.Extensions.Configuration.Binder.

Another way is to use configurationbuilder without creating commandlineconfigurationprovider to achieve the same effect directly:

var builder = new Configurationbuilder (); builder. Addcommandline (args); var item = Builder. Build (). Get<commandlineargs> (); Console.WriteLine ($ "key1={item. Key1} ");

Where Addcommandline is also an extension method, and the following four kinds have corresponding extensions, the internal implementation is actually created provider, such as the internal implementation of this method is as follows:

1 public static Iconfigurationbuilder Addcommandline (this iconfigurationbuilder configurationbuilder, string[] args) 2 { 3 Configurationbuilder.add (New Commandlineconfigurationprovider (args)); 4 return configurationbuilder;5}

To the point where the command line parameter is over, if the reader wants to know more information, you can view the corresponding source code and unit test.

B. Environmentvariables (environment variable)

Add the following dependencies in the new project (named "Environmentvariablescfg") in Project.json:

"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc1-final",

"Microsoft.Extensions.Configuration.Binder": "1.0.0-rc1-final"

It is important to note that the dependent library is a global dependent library, not a dependent library under dnx451 or DNXCORE50.

As in the previous format, let's start with a simple example of how to use it. It is believed that many people who have created a. NET core project have seen the "environment variable" in the Properties window, but do not know how to use it, and this section will use it to read the corresponding configuration information. First we create a new value in it:

Then we open the Program.cs to write the following program:

public static void Main (string[] args) {   var provider = new Environmentvariablesconfigurationprovider ();   Provider. Load ();   String value = null;   Provider. Tryget ("Con", out value);   Console.WriteLine ($ "Con={value}");   Console.readkey ();}

We can see that the way we follow the previous section is exactly the same, so that we avoid internal changes to our system as we expand ourselves in the future.

If the reader carefully review the data in the provider will find that not only save our configuration information also saved a lot of system configuration information, this is because when the load is called the internal system configuration information also read, the corresponding source code is as follows:

public override void Load () {   load (environment.getenvironmentvariables ());}

When we initialize provider we can see that constructors also support prefix, so let's use prefix to define a configuration with its own prefix to avoid conflicting with other configuration information:

var Provider = new Environmentvariablesconfigurationprovider ("CFG:");p Rovider. Load (); string value = Null;provider. Tryget ("Con", out value); Console.WriteLine ($ "Con={value}"); Console.readkey ();

The reader also has to remember that the property of the project changes the key of the variable in the environment configuration to Cfg:con, otherwise the value obtained is null.

Believe that smart readers already know how to use the corresponding, so I just list the corresponding code here (two ways).

public class Envirvarcfg {public     string Con {get; set;}}

Mode 1:

var Provider = new Environmentvariablesconfigurationprovider ("CFG:"); var builder = new Configurationbuilder (); builder. ADD (provider); var item = Builder. Build (). Get<envirvarcfg> (); Console.WriteLine ($ "con={item. Con} ");

Mode 2:

var builder = new Configurationbuilder (); builder. Addenvironmentvariables ("CFG:"); var item = Builder. Build (). Get<envirvarcfg> (); Console.WriteLine ($ "con={item. Con} ");

This is the end of this section of the environment variable, and if the reader has mastered the rules, the following sections should be mastered quickly.

C Ini

Add the following dependencies in the new project (named "Inicfg") in Project.json:

"Microsoft.Extensions.Configuration.Ini": "1.0.0-rc1-final",

"Microsoft.Extensions.Configuration.Binder": "1.0.0-rc1-final"

It is important to note that the dependent library is a global dependent library, not a dependent library under dnx451 or DNXCORE50.

First we create a new "Config.ini" file under the project root and write the following in it so we can read:

[Segone] con=localhost[segtwo]con=192.168.1.113ext:port=5535[seg:three]con=192.169.12.12

Then we open the Program.cs file and write the following code to read the contents of the configuration file:

View Code

The same many people have seen a similar configuration file, especially when building some services, then from. NET core will also be native to support these configurations, of course, the above example does not give the corresponding comments, the corresponding comments to ";", "#" and "/" to begin.

Because complex types are involved in this structure, our model may be more complex:

View Code

The first method of implementation:

            String path = Path.Combine (Directory.GetCurrentDirectory (), "Config.ini");            var Provider = new Iniconfigurationprovider (path);            var builder = new Configurationbuilder ();            Builder. ADD (provider);            var item = Builder. Build (). Get<inimodelcfg> ();            Console.WriteLine ($ "segone-con={item. Segone.con} ");            Console.WriteLine ($ "segtwo-con={item. Segtwo.con} ");            Console.WriteLine ($ "segtwo-ext:port={item. SegTwo.Ext.Port} ");            Console.WriteLine ($ "seg:three-con={item. Seg.Three.Con} ");

The second way of implementation:

            String path = Path.Combine (Directory.GetCurrentDirectory (), "Config.ini");            var builder = new Configurationbuilder ();            Builder. Addinifile (path);            var item = Builder. Build (). Get<inimodelcfg> ();            Console.WriteLine ($ "segone-con={item. Segone.con} ");            Console.WriteLine ($ "segtwo-con={item. Segtwo.con} ");            Console.WriteLine ($ "segtwo-ext:port={item. SegTwo.Ext.Port} ");            Console.WriteLine ($ "seg:three-con={item. Seg.Three.Con} ");

D. Json

Add the following dependencies in the new project (named "Jsoncfg") in Project.json:

"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",

"Microsoft.Extensions.Configuration.Binder": "1.0.0-rc1-final"

It is important to note that the dependent library is a global dependent library, not a dependent library under dnx451 or DNXCORE50.

First we create a new "Config.json" file in the project root directory and write the following in it to test:

{  "url": "localhost",  "port": {    "one": 1234, "one":    456  }}

Then open the Program.cs file and write the following in it:

            String path = Path.Combine (Directory.GetCurrentDirectory (), "Config.json");            var Provider = new Jsonconfigurationprovider (path);            Provider. Load ();            string url = null;            Provider. Tryget ("url", out URL);            Console.WriteLine ($ "Url={url}");            string one = null;            Provider. Tryget ("Port:one", out one);            Console.WriteLine ($ "Port-one={one}");            string, or null;            Provider. Tryget ("Port:two", out of both);            Console.WriteLine ($ "Port0two={two}");            Console.readkey ();

How to get the elements of an element is consistent with the INI mode, all separated by colons.

Basically the same as before, I will give the corresponding code, the first is the model-related code:

View Code

The first method of implementation:

            String path = Path.Combine (Directory.GetCurrentDirectory (), "Config.json");            var Provider = new Jsonconfigurationprovider (path);            var builder = new Configurationbuilder ();            Builder. ADD (provider);            var item = Builder. Build (). Get<jsonmodelcfg> ();            Console.WriteLine ($ "url={item. URL} ");            Console.WriteLine ($ "port-one={item. Port.one} ");            Console.WriteLine ($ "port-two={item. Port.two} ");

The second way of implementation:

View Code

E. Xml

Add the following dependencies in the new project (named "XMLCFG") in Project.json:

"Microsoft.Extensions.Configuration.Xml": "1.0.0-rc1-final",

"Microsoft.Extensions.Configuration.Binder": "1.0.0-rc1-final"

It is important to note that the dependent library is a global dependent library, not a dependent library under dnx451 or DNXCORE50.

In the project root, create a new "config.?" File and write the following in it for later testing:

<settings>  <data>    <con>123456</con>  </data>  <inventory value= " Test "/></settings>

Then open the Program.cs file and write the following code in it:

            String path = Path.Combine (Directory.GetCurrentDirectory (), "Config.");            var Provider = new Xmlconfigurationprovider (path);            Provider. Load ();            string con = null;            Provider. Tryget ("Data:con", out con);            Console.WriteLine ($ "Con={con}");            string name = NULL;            Provider. Tryget ("Inventory:value", out name);            Console.WriteLine ($ "Value={name}");            Console.readkey ();

The corresponding model bindings are no longer duplicated, exactly the same. All the configuration-related content is now complete.

. Net Core Configuration files

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.