.NET Core配置文件加載與DI注入配置數據

.NET Core配置文件

在之前.NET中配置文件都是以App.config / Web.config等XML格式的配置文件,而.NET Core中建議使用以JSON爲格式的配置文件,由於使用起來更加方面靈活,並且可使用.NET Core中的DI注入配置數據。json

使用:api

1             var config = new ConfigurationBuilder()
2                 .AddInMemoryCollection()    //將配置文件的數據加載到內存中
3                 .SetBasePath(Directory.GetCurrentDirectory())   //指定配置文件所在的目錄
4                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)  //指定加載的配置文件
5                 .Build();    //編譯成對象  
6             Console.WriteLine(config["test"]);  //獲取配置中的數據
7             config["test"] = "test test";   //修改配置對象的數據,配置對象的數據是能夠被修改的
8             Console.WriteLine(config["test11"]);    //獲取配置文件中不存在數據也是不會報錯的
9             Console.WriteLine(config["theKey:nextKey"]);    //獲取:theKey -> nextKey 的值

配置文件appsettings.json文件內容:app

1 {
2   "test": "testVal",
3   "theKey": {
4     "nextKey": "keyVal"
5   }
6 }

 注意:ide

ConfigurationBuilder須要添加包:"Microsoft.Extensions.Configuration"測試

AddJsonFile須要添加包:"Microsoft.Extensions.Configuration.Json"ui

 

與DI配合使用

 1             var sp = new ServiceCollection()
 2                 .AddOptions()   //注入IOptions<T>,這樣就能夠在DI容器中獲取IOptions<T>了
 3                 .Configure<TestCls>(config.GetSection("TestCls"))   //注入配置數據
 4                 //也能夠對注入的配置數據進行修改
 5                 .Configure<TestCls>(t =>
 6                 {
 7                     t.Name = "Jame"; //修改Name的值
 8                 })
 9                 .BuildServiceProvider();    //編譯
10 
11             var test = sp.GetService<IOptions<TestCls>>();    //獲取注入的配置數據對象
12             Console.WriteLine(JsonConvert.SerializeObject(test.Value));    //{"Name":"Jame","Age":123}
13 
14             //下面的代碼中檢驗Configure注入的配置數據對象是單例模式的(.NET Core中DI容器的三種生命週期:Singleton(單例), Scoped(做用域), Transient(瞬態))
15             var test1 = sp.GetService<IOptions<TestCls>>();
16             Console.WriteLine(test == test1);   //true
17             //建立一個新的做用域獲取配置數據對象
18             var test2 = sp.GetService<IServiceScopeFactory>().CreateScope().ServiceProvider.GetService<IOptions<TestCls>>();
19             Console.WriteLine(test == test2);   //true

 配置測試類:spa

1         public class TestCls
2         {
3             public string Name { get; set; }
4             public int Age { get; set; }
5         }

appsettings.json中的內容:code

1 {
2   "TestCls": {
3     "Name": "Tom",
4     "Age": 123
5   }
6 }

注意:orm

ServiceCollection須要添加包: "Microsoft.Extensions.DependencyInjection"對象

AddOptions須要添加包: "Microsoft.Extensions.Options.ConfigurationExtensions"

 

ASP.NET Core中使用

Startup.cs -> Startup構造方法中進行初始化配置文件:

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();

Startup.cs -> ConfigureServices方法中進行注入配置數據:

1             services.AddOptions()        //注入IOptions<T>
2                 .Configure<TestCls>(Configuration.GetSection(nameof(TestCls)))
3                 .Configure<TestCls>(test =>
4                 {
5                     test.Name = "Jame"; //修改Name的值
6                 });

配置文件中的配置數據:

 1 {
 2   "Logging": {
 3     "IncludeScopes": false,
 4     "LogLevel": {
 5       "Default": "Debug",
 6       "System": "Information",
 7       "Microsoft": "Information"
 8     }
 9   },
10   "TestCls": {
11     "Name": "Tom",
12     "Age": 123
13   }
14 }

注入到控制器中:

 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()
11         {
12             return JsonConvert.SerializeObject(_test.Value);
13         }

訪問:/api/values

顯示:{"Name":"Jame","Age":123}

相關文章
相關標籤/搜索