给IConfiguration写一个GetAppSetting扩展方法

时间:2021-12-17 11:12:22

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}");

Memo

你可以复制上面的代码在你自己的代码里使用,也可以直接使用 WeihanLi.Common 这一 nuget 包