. 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:

1             var config = new Configurationbuilder () 2                 . Addinmemorycollection ()    //load the data of the configuration file into memory 3                 . Setbasepath (Directory.GetCurrentDirectory ())   //Specify the directory where the configuration file is located 4                 . Addjsonfile ("Appsettings.json", Optional:true, Reloadonchange:true)  //Specify the configuration file to load 5                 . Build ();    Compiled into Object  6             Console.WriteLine (config["Test"]);  Gets the data in the configuration 7             config["test"] = "test test";   Modify the data of the configuration object, the data of the configuration object is 8             Console.WriteLine (config["test11") that can be modified;    9             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:

1 {2   "test": "TestVal", 3   "Thekey": {4     "Nextkey": "Keyval" 5   }6}

Attention:

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

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

Use with Di
 1 var sp = new Servicecollection () 2. AddOptions ()///inject ioptions<t&gt, so you can get ioptions<t> 3 in the Di container. configure<testcls> (config. GetSection ("Testcls"))//injection configuration Data 4//can also be modified to the injected configuration data 5. Configure<testcls> (t = 6 {7 T.name = "Jame";//Modify the value of Name 8} ) 9.    Buildserviceprovider (); Compile ten var test = sp.    Getservice<ioptions<testcls>> (); Gets the injected configuration data object, Console.WriteLine (Test. Jsonconvert.serializeobject).    Value)); {"Name": "Jame", "Age": 123}13 14//The following code verifies that the configuration data object injected by configure is in Singleton mode (three lifecycles for the Di container in. NET Core: Singleton (singleton), Scope D (Scope), Transient (transient)), var test1 = sp.   Getservice<ioptions<testcls>> (); Console.WriteLine (test = = test1); TRUE17//Create a new scope gets the configuration data object at var test2 = sp. Getservice<iservicescopefactory> (). Createscope ().   Serviceprovider.getservice<ioptions<testcls>> (); Console.WriteLine (test = = test2); True

To configure the test class:

1 public         class TESTCLS2         {3 public             string Name {get; set;} 4 public             int age {get; set;} 5         }

Content in Appsettings.json:

1 {2   "Testcls": {3     "Name": "Tom", 4     "age": 1235   }6}

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:

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

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

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

Configuration data in the configuration file:

1 {2   "Logging": {3     "Includescopes": false, 4     "LogLevel": {5       "Default": "Debug", 6       "System": "Infor Mation ", 7       " Microsoft ":" Information "8     } 9   },10   " Testcls ": {one     " Name ":" Tom ",     " age ": 12313   }14}

Injection into the controller:

1     [Route ("Api/[controller]")] 2 public     class Valuescontroller:controller 3     {4         ioptions< Testcls> _test; 5 Public         Valuescontroller (ioptions<testcls> test) 6         {7             _test = test; 8         } 9         [httpget]10 Public         string Gets ()         One {             return Jsonconvert.serializeobject (_test). Value);         

. NET core configuration file loading with di injection configuration data

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.