一、扩展步骤
1.实现 IConfigurationProvider
class MyConfigurationProvider : ConfigurationProvider { Timer timer; public MyConfigurationProvider() : base() { timer = new Timer(); timer.Elapsed += Timer_Elapsed; timer.Interval = 3000; timer.Start(); } private void Timer_Elapsed(object sender, ElapsedEventArgs e) { Load(true); } public override void Load() { //加载数据 Load(false); } void Load(bool reload) { this.Data["lastTime"] = DateTime.Now.ToString(); if (reload) { base.OnReload(); } } }
2.实现 IConfigurationSource
class MyConfigurationSource : IConfigurationSource { public IConfigurationProvider Build(IConfigurationBuilder builder) { return new MyConfigurationProvider(); } }
3.实现 AddXXX 扩展方法
public static class MyConfigurationBuilderExtensions { public static IConfigurationBuilder AddMyConfiguration(this IConfigurationBuilder builder) { builder.Add(new MyConfigurationSource()); return builder; } }
4.使用
static void Main(string[] args) { var builder = new ConfigurationBuilder(); builder.AddMyConfiguration(); var configRoot = builder.Build(); ChangeToken.OnChange(() => configRoot.GetReloadToken(), () => { Console.WriteLine($"lastTime:{configRoot["lastTime"]}"); }); Console.ReadKey(); }