給 寫一個 擴展方法 Intro 在 .net core 中,微軟已經預設使用 appsettings.json 來代替 app.config,並重新設計了一套完整的配置系統,可以支持 json/xml/ini/環境變數等。 在 .net core 中有一個 的擴展方法用來比較方便的獲取鏈接字元串, ...
給 IConfiguration
寫一個 GetAppSetting
擴展方法
Intro
在 .net core 中,微軟已經預設使用 appsettings.json 來代替 app.config,並重新設計了一套完整的配置系統,可以支持 json/xml/ini/環境變數等。
在 .net core 中有一個 GetConnectionString
的擴展方法用來比較方便的獲取鏈接字元串,類似於在 .net framework 中使用 ConfigurationManager.ConnectionStrings["key"]
來獲取鏈接字元串。
這次來參考 GetConnectionString
實現一個 GetAppSetting
,類似於 .net framework 中使用 ConfigurationManager.AppSettings
來獲取配置值。
實現代碼
GetConnectionString
是獲取 ConnectionStrings
這個節點下的某個配置,
GetAppSetting
來獲取 AppSettings
這個節點下的某個配置
實現代碼:
/// <summary>
/// GetAppSetting
/// Shorthand for GetSection("AppSettings")[key]
/// </summary>
/// <param name="configuration">IConfiguration instance</param>
/// <param name="key">appSettings key</param>
/// <returns>app setting value</returns>
public static string GetAppSetting([NotNull]this IConfiguration configuration, string key)
{
return configuration.GetSection("AppSettings")[key];
}
/// <summary>
/// GetAppSetting
/// Shorthand for GetSection("AppSettings")[key]
/// </summary>
/// <param name="configuration">IConfiguration instance</param>
/// <param name="key">appSettings key</param>
/// <returns>app setting value</returns>
public static T GetAppSetting<T>([NotNull]this IConfiguration configuration, string key)
{
return configuration.GetSection("AppSettings")[key].To<T>();
}
/// <summary>
/// GetAppSetting
/// Shorthand for GetSection("AppSettings")[key]
/// </summary>
/// <param name="configuration">IConfiguration instance</param>
/// <param name="key">appSettings key</param>
/// <param name="defaultValue">default value if not exist</param>
/// <returns>app setting value</returns>
public static T GetAppSetting<T>([NotNull] this IConfiguration configuration, string key, T defaultValue)
{
return configuration.GetSection("AppSettings")[key].ToOrDefault(defaultValue);
}
/// <summary>
/// GetAppSetting
/// Shorthand for GetSection("AppSettings")[key]
/// </summary>
/// <param name="configuration">IConfiguration instance</param>
/// <param name="key">appSettings key</param>
/// <param name="defaultValueFunc">default value func if not exist to get a default value</param>
/// <returns>app setting value</returns>
public static T GetAppSetting<T>([NotNull] this IConfiguration configuration, string key, Func<T> defaultValueFunc)
{
return configuration.GetSection("AppSettings")[key].ToOrDefault(defaultValueFunc);
}
使用
使用起來和 GetConnectionString
差不多
測試 appsettings.json
{
"ConnectionStrings": {
"TestDb": "server=.;database=Test;uid=weihanli;pwd=Admin888"
},
"AppSettings":{
"Number": 12,
"City": "Shanghai"
}
}
GetAppSetting 示例
IConfiguration configuration = new ConfigurationBuilder()
// ...
.AddJsonFile("appsettings.json")
.Build();
var city = configuration.GetAppSetting("City");
var number = configuration.GetAppSetting<int>("Number");
System.Console.WriteLine($"City:{city}, Number:{number}");