1.新增Microsoft.Extensions.Configuration包
在启动项目下,设置appsettings.json属性为始终复制
2.新建一个文件夹Common,用于存放工具类项目。并且新建项目:Ysq.Core.AppSettings,引用package包项目,然后新建一个读取配置文件的通用类,叫AppHelper。目录结构如图
3.AppHelper代码如下:
点击查看代码
using Microsoft.Extensions.Configuration;
namespace Ysq.Core.AppSettings
{
public class AppHelper
{
private IConfiguration _config;
// 静态单例实例
private static AppHelper _instance;
// 私有构造函数,防止外部直接实例化
private AppHelper(IConfiguration configuration)
{
_config = configuration;
}
/// <summary>
/// 初始化 AppHelper 单例实例
/// </summary>
/// <param name="configuration"></param>
public static void Init(IConfiguration configuration)
{
if (_instance == null)
{
_instance = new AppHelper(configuration);
}
}
/// <summary>
/// 获取 AppHelper 单例实例
/// </summary>
public static AppHelper Instance
{
get
{
if (_instance == null)
{
throw new InvalidOperationException("AppHelper 未初始化,请先调用 Init 方法进行初始化");
}
return _instance;
}
}
/// <summary>
/// 读取指定节点的字符串
/// </summary>
/// <param name="sessions"></param>
/// <returns></returns>
public string ReadAppSettings(params string[] sessions)
{
try
{
if (sessions.Any())
{
return _config[string.Join(":", sessions)];
}
}
catch
{
return "";
}
return "";
}
/// <summary>
/// 读取实体信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="session"></param>
/// <returns></returns>
public List<T> ReadAppSettings<T>(params string[] session)
{
List<T> list = new List<T>();
_config.Bind(string.Join(":", session), list);
return list;
}
}
}
4.在Program中初始化AppHelper单例
5.新增一段配置文件添加测试方法
6.输出