.NET6开发WebAPI笔记—通用类中使用appsettings.json中的数据
开发的过程中有时候需要在其他类库中使用appsettings.json中配置的值。举个小栗子:我写了一个简单的工厂,根据appsettings.json的配置,来判断是应该使用内存缓存还是Redis来做缓存,那么这时候就需要在工厂类里获取appsettings.json的Cache配置:
这是appsetting.json中的配置项:
//缓存方式
"CacheProvider": "Redis"
创建一个AppSettings.cs类,代码直接记在下面:
public class AppSettings
{
static IConfiguration Configuration { get; set; }
public AppSettings(IConfiguration configuration)
{
Configuration = configuration;
}
/// <summary>
/// 封装要操作的字符
/// </summary>
/// <param name="sections">节点配置</param>
/// <returns></returns>
public static string App(params string[] sections)
{
try
{
if (sections.Any())
{
return Configuration[string.Join(":", sections)];
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return "";
}
/// <summary>
/// 递归获取配置信息数组
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sections"></param>
/// <returns></returns>
public static List<T> App<T>(params string[] sections)
{
List<T> list = new();
// 引用 Microsoft.Extensions.Configuration.Binder 包
Configuration.Bind(string.Join(":", sections), list);
return list;
}
public static T Bind<T>(string key, T t)
{
Configuration.Bind(key, t);
return t;
}
public static T GetAppConfig<T>(string key, T defaultValue = default)
{
T setting = (T)Convert.ChangeType(Configuration[key], typeof(T));
var value = setting;
if (setting == null)
value = defaultValue;
return value;
}
/// <summary>
/// 获取配置文件
/// </summary>
/// <param name="key">eg: WeChat:Token</param>
/// <returns></returns>
public static string GetConfig(string key)
{
return Configuration[key];
}
}
然后在Program.cs中配置一下:
builder.Services.AddSingleton(new AppSettings(builder.Configuration));
最后是使用:
switch (AppSettings.GetConfig("CacheProvider"))
{
case "Redis": cache = new RedisCacheImp(); break;
default:
case "Memory": cache = new MemoryCacheImp(); break;
}