ASP. 5 Getting Started (2) – Custom Configuration

Source: Internet
Author: User

Original: ASP. 5 Getting Started (2) – Custom Configuration

ASP. 5 Getting Started (2) – Custom Configuration

ASP. 5 Understanding and Getting Started

Build and develop an ASP 5 project

Initial understanding of ASP.NET5 configuration

As my first article, ASP. NET 5 (VNext) understands and outlines, ASP. NET 5 has a completely new configuration mechanism that we can understand through the following points:

    1. Supports multiple cross-platform configuration file formats (e.g. XML, Json, INI, and environment variables)
    2. Standard configuration files, such as Project.json, no longer include any custom configuration information.
    3. Custom configurations are created and loaded entirely by the developer
    4. Custom configuration information can be distributed through dependency injection to the entire project
Create a custom configuration file

First we add a custom configuration file at the root of the project, Config.json and Config.ini (the file name here can be arbitrarily defined).

Config.json's content we simulate the following

{  "AppSettings": {    "Sitetitle": "ASP. 5 Sample"  }  ,"Data":    { "DefaultConnection": {      "ConnectionString": "Server= (LocalDB) \\mssqllocaldb;database=aspnet5; Trusted_connection=true; Multipleactiveresultsets=true "    }}  }


Config.ini's content we simulate as follows:

Defaultpage=index.html

Load configuration file

As mentioned before, we typically load a configuration file by using the constructor of the startup class. The configuration file for the startup class is generally defined as such.

      Public Startup (ihostingenvironment env)      {      }


In the minimal template, if you read the JSON and INI files, we need to add the Configurationmodel.json components:

Then we can add the following code to read any JSON file, INI file, and system environment variable

 public   Startup (ihostingenvironment env)             { //  load custom JSON configuration file and ini config file  var  configuration = new   Configuration (). Addjsonfile (  config.json   " ). Addinifile (  config.ini   " );  //  add system environment variable   configuration.        Addenvironmentvariables (); }

Using configuration information

After loading, the configuration variables generated in the above code can be used to read various configurations conveniently, and here, in the configuration information saved by the object structure, the Config class uses ":" To realize the navigation of the object properties. Don't quite understand the following code can be seen:

           //try to output some configuration information//corresponding to the Data.DefaultConnection.ConnectionString of Config.jsonConsole.WriteLine (configuration["Data:DefaultConnection:ConnectionString"]); //corresponding to the defaultpage of Config.iniConsole.WriteLine (configuration["Defaultpage"]); //path within the corresponding system environmentConsole.WriteLine (configuration["Path"]);

mount configuration to Environment container

In the startup class, we can easily pass a configuration variable through a member variable, the more common notation can resemble the following code

        PrivateIConfiguration Configuration {Get;Set; }  PublicStartup (ihostingenvironment env) {//loading a custom JSON configuration file and INI configuration file            varConfiguration =NewConfiguration (). Addjsonfile ("Config.json")                . Addinifile ("Config.ini"); //adding environment variables to the systemconfiguration.            Addenvironmentvariables (); //assigning values to member variablesConfiguration =configuration; }

However, if you want to use dependency injection technology to load configuration information into an environment container throughout the project, you can make flexible calls throughout your project.

In my previous post's description of the startup class, the Configureservices function that mentioned startup was the one that was responsible for loading all the dependent injection services, so we needed to add the loading code there:

       Public void configureservices (iservicecollection services)        {            // put the configuration object into service container services            . Addinstance (typeof(iconfiguration), Configuration);        }


Note that the configration here is a member variable.

Using configurations in other regions

How do I use configuration information elsewhere in the project? We typically have 2 options for the dependency injection method for ASP. NET 5.

    1. It is slightly obscure, but very concise, to implicitly load other service elements by extending the parameters of any constructor of an object in the same container. (This will be discussed again in the future MVC 6 and EF 7 introductions.)
    2. The corresponding service element is obtained through the ApplicationServices attribute in the current context (which can be obtained by our old friend HttpContext in many cases).

Here we have not loaded MVC or EF, and we are going to use the Configure function of the startup class to do a demonstration:

Example of the first pattern code:

       Public void Configure (iapplicationbuilder app,iconfiguration configuration)        {            // read out configuration information            from the current container Console.WriteLine (configuration["defaultpage"]);            Console.WriteLine (configuration["appsettings:sitetitle");        }


Note that the implicit conversion of the IConfiguration configuration parameter is because we have previously added the configuration to the service container. If there is no previous registration, the code here will be an error.

Example of the second pattern code:

 public  void   Configure (Iapplicationbuilder app) { var  configuration = (iconfiguration) app. Applicationservices.getservice (typeof   (            IConfiguration));  //  read configuration information from the current container  Console.writeli NE (Configuration[ " defaultpage   " ]); Console.WriteLine (configuration[          Appsettings:sitetitle   


In the following common objects, such as the MVC controller, and EF's dbcontext, we are able to conveniently use these 2 ways to get configuration information for the entire project.

Well, using the method mentioned above, we have the flexibility to set up configuration files, load configuration files, and use configuration information in an ASP. NET 5 project, and we can further encapsulate the configuration information based on the MVC service.

ASP.NET5 configuration mechanism is not very convenient. Does anyone else miss Web. config?

ASP. 5 Getting Started (2) – Custom 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.