/// <summary>
/// 基于netcore配置框架的文件监控帮助类 XQX
/// </summary>
public class FileWatchHelper<T>
{
private IConfiguration _configuration;
/// <summary>
/// 文件实体
/// </summary>
public T FileEntity = (T)Activator.CreateInstance(typeof(T));
/// <summary>
/// 构造方法
/// </summary>
/// <param name=”path”>文件路径</param>
/// <param name=”optional”>文件是否可选</param>
/// <param name=”reloadOnChange”>是否热更新</param>
/// <param name=”action”>文件变化时触发的事件</param>
public FileWatchHelper(string path, Action action = null, bool optional = false, bool reloadOnChange = true)
{
var builder = new ConfigurationBuilder()
.AddJsonFile(path, optional: false, reloadOnChange: true);
_configuration = builder.Build();
//绑定实体
_configuration.Bind(FileEntity, BinderOptions => { BinderOptions.BindNonPublicProperties = true; });
#region 监听文件的改动
ChangeToken.OnChange(() => _configuration.GetReloadToken(), () =>
{
//重新绑定实体
_configuration.Bind(FileEntity, BinderOptions => { BinderOptions.BindNonPublicProperties = true; });
action?.Invoke();
});
#endregion
}
}
原创文章,作者:sunnyman218,如若转载,请注明出处:https://blog.ytso.com/270923.html