asp.net core配置項示例程式碼
阿新 • • 發佈:2021-12-14
IConfigurationBuilder
用於Build IConfigurationRoot(從IConfiguration繼承)
物件。IConfigurationBuilder介面中維護了一系列的IConfigurationSource
列表, 每種IConfigurationSource
提供配置項的資料來源,IConfigurationSource.Build
生成的IConfigurationProvider
用於從當前配置源中讀取key-value值
static void Main(string[] args) { //1、建立IConfigurationBuilder IConfigurationBuilder builder = new ConfigurationBuilder(); //2、建立配置源並新增到Builder中 IConfigurationSource //2、1系統自帶的IConfigurationSource List<KeyValuePair<string, string>> InitialData = new List<KeyValuePair<string, string>>(); InitialData.Add(new KeyValuePair<string, string>("name", "caoruipeng")); InitialData.Add(new KeyValuePair<string, string>("info:age", "29")); InitialData.Add(new KeyValuePair<string, string>("info:school", "北華大學")); InitialData.Add(new KeyValuePair<string, string>("user:name", "北華大學")); IConfigurationSource source = new MemoryConfigurationSource() { InitialData = InitialData }; builder.Add(source); //2、2自定義IConfigurationSource IDictionary<string, string> data = new Dictionary<string, string>(); data.Add("dbkey", "dbvalue"); IConfigurationSource dbSource = new DBConfigurationSource(data); builder.Add(dbSource); //3、建立key-value集合 IConfigurationRoot configuration = builder.Build(); //4、獲取key-value string value = configuration["name"]; value = configuration.GetValue<string>("name"); Console.WriteLine($"key:name,value:{value}"); value = configuration.GetValue<string>("dbkey"); Console.WriteLine($"key:dbkey,value:{value}"); IConfigurationSection section = configuration.GetSection("info"); } /// <summary> /// 自定義配置源 /// </summary> public class DBConfigurationSource : IConfigurationSource { IDictionary<string, string> data = new Dictionary<string, string>(); public DBConfigurationSource(IDictionary<string, string> data) { this.data = data; } public IConfigurationProvider Build(IConfigurationBuilder builder) { return new DBConfigurationProvider(data); } } /// <summary> /// 自定義配置源的Provider,用於從配置源中讀取key-value值 /// </summary> public class DBConfigurationProvider : ConfigurationProvider { public DBConfigurationProvider(IDictionary<string, string> data) { Data = data; } public override void Load() { base.Load(); } }