. NET core configuration file loading with di injection configuration data

Source: Internet
Author: User

. NET Core Configuration files

In the past. NET is a configuration file in XML format such as App.config/web.config, and. NET core recommends using a JSON-formatted configuration file because it is more flexible to use, and you can use DI injection configuration data from. NET Core.

Use:

var config = new Configurationbuilder ()                . Addinmemorycollection ()    //load the data of the configuration file into memory                . Setbasepath (Directory.GetCurrentDirectory ())   //Specifies the directory where the configuration file resides                . Addjsonfile ("Appsettings.json", Optional:true, Reloadonchange:true)  //Specify the configuration file to load                . Build ();    Compiled into Object              Console.WriteLine (config["Test"]);  Gets the data in the configuration            config["test"] = "test test";   Modify the Configuration object data, configuration object data is can be modified            Console.WriteLine (config["test11"]);            Console.WriteLine (config["Thekey:nextkey"])    to obtain data that does not exist in the configuration file and does not error. Get: Thekey---Nextkey value

Configuration file Appsettings.json file contents:

{  "test": "TestVal",  "Thekey": {    "Nextkey": "Keyval"  }}

Attention:

Configurationbuilder need to add Package: "Microsoft.Extensions.Configuration"

Addjsonfile need to add Package: "Microsoft.Extensions.Configuration.Json"

Use with Di

var sp = new Servicecollection (). AddOptions ()//inject ioptions<t&gt, so you can get ioptions<t> in the Di container. configure<testcls> (config. GetSection ("Testcls"))//injection configuration Data//can also modify the injected configuration data.                configure<testcls> (t = = {T.name = "Jame";//Modify the value of Name}) .    Buildserviceprovider (); Compile var test = sp.    Getservice<ioptions<testcls>> (); Gets the injected configuration data Object Console.WriteLine (Jsonconvert.serializeobject (Test.    Value)); {"Name": "Jame", "Age": 123}//The following code verifies that the configuration data object injected by configure is in Singleton mode (three lifecycles of the Di container in. NET Core: Singleton (Singleton), Scoped (Scope) , Transient (transient)) var test1 = sp.            Getservice<ioptions<testcls>> ();   Console.WriteLine (test = = test1); True//Create a new scope to get the configuration data object var test2 = sp. Getservice<iservicescopefactory> (). Createscope (). Serviceprovider.getservice<ioptions<testcls&gT;> ();   Console.WriteLine (test = = test2); True

To configure the test class:

         public class Testcls         {public             string Name {get; set;}             public int Age {get; set;}         }

Content in Appsettings.json:

{"  testcls": {    "Name": "Tom",    "age": 123  }}

Attention:

Servicecollection need to add Package: "Microsoft.Extensions.DependencyInjection"

AddOptions need to add Package: "Microsoft.Extensions.Options.ConfigurationExtensions"

Use in ASP. NET Core

Initialize the configuration file in the startup construction method, Startup.cs:

var builder = new Configurationbuilder ()                . Addinmemorycollection ()                . Setbasepath (env. Contentrootpath)                . Addjsonfile ("Appsettings.json", Optional:true, Reloadonchange:true)                . Addjsonfile ($ "appsettings.{ Env. Environmentname}.json ", optional:true);            Configuration = Builder. Build ();

Injection configuration data in the Startup.cs-I configureservices method:

Services. AddOptions ()        //inject ioptions<t>                . Configure<testcls> (Configuration.getsection (nameof (TESTCLS)))                . configure<testcls> (test =                {                    test). Name = "Jame"; Modify the value of name                });

Configuration data in the configuration file:

{"  Logging": {    "includescopes": false,    "LogLevel": {      "Default": "Debug",      "System": "Information ",      " Microsoft ":" Information "    }  ,  " Testcls ": {    " Name ":" Tom ",    " age ": 123  }}

Injection into the controller:

[Route ("Api/[controller]")]    public class Valuescontroller:controller    {        ioptions<testcls> _test;        Public Valuescontroller (ioptions<testcls> test)        {            _test = test;        }        [HttpGet]        public string Gets ()        {            return Jsonconvert.serializeobject (_test). Value);        }

Visit:/api/values

Display: {"Name": "Jame", "Age": 123}

"Recommended"

1.. Net Core Graphics Verification Code

2.. NET Core CLI Tool documentation Dotnet-publish

3. Detailed introduction to ZKEACMS for. Net Core

4. Sharing. NET MVC using forms to validate instance code

5. How do I make HTTP requests under. NET Core?

6. Example tutorials for running zkeacms on CentOS

  • Related Article

    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.