dotnetcore配置框架簡介

一、前言

配置的本質就是字符串的鍵值對,微軟的一系列接口其實就是對這些鍵值對字符串的抽象。 

二、基本類型

2.1、Nuget包

  • Microsoft.Extensions.Configuration.Abstractions
  • Microsoft.Extensions.Configuration

2.2、抽象接口

  • IConfiguration
    • 提供了查詢、設置配置項、監控變化等方法
  • IConfigurationRoot
    • 在IConfiguration接口基礎上,增加了 Reload 方法強制從provider中重新加載配置值
  • IConfigurationSection
    • 對配置節點的抽象
  • IConfigurationBuilder
    • 根據提供的數據源註冊並構建IConfiguration
  • IConfigurationSource
    • 對數據源的抽象,例如Json、xml、環境變量、內存變量等
  • IConfigurationProvider
    • 規定了配置項的獲取、設置、重載等統一的行為 

 

三、基本配置

註:各種配置方式的目的是在控制台中輸出以下內容,如下圖:

image.png

3.1、加載內存中的配置

  • 需要引入包:Microsoft.Extensions.Configuration
  • 主要方法:builder.AddInMemoryCollection()
static void Main(string[] args)
{
    IConfigurationBuilder builder = new ConfigurationBuilder();
    var memoryData = new Dictionary<string, string>();
    memoryData.Add("Student:Code", "10002385");
    memoryData.Add("Student:Name", "LiuSan");

    builder.AddInMemoryCollection(memoryData);
    IConfigurationRoot configurationRoot = builder.Build();
    IConfigurationSection configurationSection = configurationRoot.GetSection("Student");

    Console.WriteLine($"Code:{configurationSection["Code"]}");
    Console.WriteLine($"Name:{configurationSection["Name"]}");        

    Console.Read();
}

 

3.2、加載環境變量中的配置

  • 需要引入包:Microsoft.Extensions.Configuration.EnvironmentVariables
  • 主要方法:builder.AddEnvironmentVariables()
  • 環境變量中層級關係使用 __ 代替 :

image.png

 

 1 static void Main(string[] args)
 2 {
 3     IConfigurationBuilder builder = new ConfigurationBuilder();
 4     builder.AddEnvironmentVariables();
 5     IConfigurationRoot configurationRoot = builder.Build();
 6     IConfigurationSection configurationSection = configurationRoot.GetSection("Student");
 7 
 8     Console.WriteLine($"Code:{configurationSection["Code"]}");
 9     Console.WriteLine($"Name:{configurationSection["Name"]}");
10 
11     Console.Read();
12 }

 

3.3、加載命令行中的配置

  • 需要引入包:Microsoft.Extensions.Configuration.CommandLine
  • 主要方法:builder.AddCommandLine(args)
  • 命令行中使用–表示配置項,層級關係使用:

image.png

 

 1 static void Main(string[] args)
 2 {
 3     IConfigurationBuilder builder = new ConfigurationBuilder();
 4     builder.AddCommandLine(args);
 5     IConfigurationRoot configurationRoot = builder.Build();
 6     IConfigurationSection configurationSection = configurationRoot.GetSection("Student");
 7 
 8     Console.WriteLine($"Code:{configurationSection["Code"]}");
 9     Console.WriteLine($"Name:{configurationSection["Name"]}");
10 
11     Console.Read();
12 }

 

3.4、加載Json中的配置

  • 需要引入包:Microsoft.Extensions.Configuration.Json
  • 主要方法:builder.AddJsonFile(“appsettings.json”)

image.png

 

 1 static void Main(string[] args)
 2 {
 3     IConfigurationBuilder builder = new ConfigurationBuilder();
 4     builder.AddJsonFile("appsettings.json");
 5     IConfigurationRoot configurationRoot = builder.Build();
 6     IConfigurationSection configurationSection = configurationRoot.GetSection("Student");
 7 
 8     Console.WriteLine($"Code:{configurationSection["Code"]}");
 9     Console.WriteLine($"Name:{configurationSection["Name"]}");
10 
11     Console.Read();
12 }

 

3.5、加載xml中的配置

  • 需要引入包:Microsoft.Extensions.Configuration.Xml
  • 主要方法:builder.AddXmlFile(“appsettings.xml”)
  • xml中不會讀取最外層,所以Section必需從第二層開始

image.png

 

 1 static void Main(string[] args)
 2 {
 3     IConfigurationBuilder builder = new ConfigurationBuilder();
 4     builder.AddXmlFile("appsettings.xml");
 5     IConfigurationRoot configurationRoot = builder.Build();
 6     IConfigurationSection configurationSection = configurationRoot.GetSection("Student");
 7 
 8     Console.WriteLine($"Code:{configurationSection["Code"]}");
 9     Console.WriteLine($"Name:{configurationSection["Name"]}");
10 
11     Console.Read();
12 }

 

四、高級配置

4.1、將配置綁定至強對象

  • 需要引入包:Microsoft.Extensions.Configuration.Binder
  • 主要方法:configurationRoot.GetSection(“Student”).Bind(student)
 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             IConfigurationBuilder builder = new ConfigurationBuilder();
 6             builder.AddJsonFile("appsettings.json");
 7             IConfigurationRoot configurationRoot = builder.Build();
 8 
 9             var student = new Student();
10             configurationRoot.GetSection("Student").Bind(student);
11 
12             Console.WriteLine($"Code:{student.Code}");
13             Console.WriteLine($"Name:{student.Name}");
14 
15             Console.Read();
16         }
17     }
18 
19     class Student
20     {
21         public string Code { get; set; }
22 
23         public string Name { get; set; }
24     }

 

4.2、IOptions

  • 需要引入包:Microsoft.Extensins.Options
  • 需要引入包:Microsoft.Extensions.Options.ConfigurationExtensions
  • 本質其實就是將一個Section配置節點映射到一個實體對象

image.png

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             IConfigurationBuilder builder = new ConfigurationBuilder();
 6             builder.AddJsonFile("appsettings.json");
 7             IConfigurationRoot configurationRoot = builder.Build();
 8 
 9             IServiceCollection services = new ServiceCollection();
10             services.Configure<WeixinOptions>(configurationRoot.GetSection("WeixinSetting"));
11             services.AddScoped<IWeixinService, WeixinService>();
12 
13             var provider = services.BuildServiceProvider();
14             var weixinService = provider.GetService<IWeixinService>();
15             string appId = weixinService.AppId;
16             string token = weixinService.Token;
17 
18             Console.Read();
19         }
20     }
21 
22     interface IWeixinService
23     {
24         string AppId { get; }
25         string Token { get; }
26     }
27 
28     class WeixinService: IWeixinService
29     {
30         IOptions<WeixinOptions> _options;
31         public WeixinService(IOptions<WeixinOptions> options)
32         {
33             _options = options;
34         }
35 
36         public string AppId { get => _options.Value.AppId; }
37         public string Token { get => _options.Value.Token;}
38     }
39 
40     class WeixinOptions
41     {
42         public string AppId { get; set; }
43 
44         public string Token { get; set; }
45     }

 

4.3、熱更新

  • IConfigurationBuilder添加數據源時設置reloadOnChange=true
  • 監聽的核心方法:var token = configurationRoot.GetReloadToken()
 1 static void Main(string[] args)
 2         {
 3             IConfigurationBuilder builder = new ConfigurationBuilder();
 4             builder.AddJsonFile("appsettings.json", optional:false, reloadOnChange:true);
 5             IConfigurationRoot configurationRoot = builder.Build();
 6             IConfigurationSection configurationSection = configurationRoot.GetSection("Student");
 7 
 8             var token = configurationRoot.GetReloadToken();
 9             ChangeToken.OnChange(() => configurationRoot.GetReloadToken(), () => 
10             {
11                 Console.WriteLine("配置發生改變了...");
12                 Console.WriteLine($"Code:{configurationSection["Code"]}");
13                 Console.WriteLine($"Name:{configurationSection["Name"]}");
14             });           
15 
16             Console.Read();
17         }

 

五、總結

  • 配置就是key-value鍵值對字符串
  • IConfiguration和IConfigurationRoot是對鍵值對的抽象
  • IConfigurationBuilder用於構建IConfiguration和IConfigurationRoot
  • IConfigurationSource是對數據源的抽象
  • IConfigurationProvider將不同來源的IConfigurationSource 轉為統一的模型
  • IOptions方便將不同的配置節點(Path)映射為對應的強類型對象
  • IConfigurationBuilder添加多個數據源(IConfigurationSource)後,如果key重名,則以最後一個配置為準(覆蓋前面)

更多精彩文章,請關注我的公眾號: