. 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             varConfig =NewConfigurationbuilder ()2. Addinmemorycollection ()//to load the data of a configuration file into memory3. Setbasepath (Directory.GetCurrentDirectory ())//Specify the directory where the configuration file resides4. Addjsonfile ("Appsettings.json", Optional:true, Reloadonchange:true)//Specify the configuration file to load5. Build ();//compiling into Objects6Console.WriteLine (config["Test"]);//get the data in the configuration7config["Test"] ="test test";//Modify the data of the configuration object, the data of the configuration object can be modified8Console.WriteLine (config["test11"]);//getting data that doesn't exist in the configuration file is not an error.9Console.WriteLine (config["Thekey:nextkey"]);//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             varSP =Newservicecollection ()2. AddOptions ()//inject Ioptions<t>, so you can get ioptions<t> in the Di container.3. configure<testcls> (config. GetSection ("Testcls"))//Inject configuration Data4                 //you can also make modifications to the injected configuration data5. Configure<testcls> (t =6                 {7T.name ="Jame";//Modify the value of name8                 })9. Buildserviceprovider ();//compilingTen  One             varTest = sp. Getservice<ioptions<testcls>> ();//gets the injected configuration data Object AConsole.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 life cycles of Di containers in. NET Core: Singleton (Singleton), Scoped (Scope), Transient (transient)) the             varTest1 = sp. Getservice<ioptions<testcls>>(); -Console.WriteLine (test = = test1);//true -             //Create a new scope get the configuration data Object -             varTest2 = sp. Getservice<iservicescopefactory> (). Createscope (). Serviceprovider.getservice<ioptions<testcls>>(); +Console.WriteLine (test = = test2);//true

To configure the test class:

1          Public class Testcls 2         {3public             stringgetset;} 4              Public int Get Set ; } 5         }

Content in Appsettings.json:

1 {2   " Testcls " : {3     " Name " " Tom " , 4     "  Age " 123 5   }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             varBuilder =NewConfigurationbuilder ()2                 . Addinmemorycollection ()3                 . Setbasepath (env. Contentrootpath)4. Addjsonfile ("Appsettings.json", Optional:true, Reloadonchange:true)5. Addjsonfile ($"appsettings. {env. Environmentname}.json", Optional:true);6Configuration = Builder. Build ();

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

1             Services. AddOptions ()        // injected ioptions<t>2                 . Configure<testcls>(Configuration.getsection (nameof (TESTCLS))3                 . configure<testcls> (test =4                {5                     "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":"Information",7       "Microsoft":"Information"8     }9   },Ten   "Testcls": { One     "Name":"Tom", A     " Age":123 -   } -}

Injection into the controller:

1[Route ("Api/[controller]")]2      Public classValuescontroller:controller3     {4Ioptions<testcls>_test;5          PublicValuescontroller (ioptions<testcls>test)6         {7_test =test;8         }9 [HttpGet]Ten          Public stringGets () One         { A             returnJsonconvert.serializeobject (_test. Value); -}

Visit:/api/values

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

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