MyConfigurationSource:
class MyConfigurationSource : IConfigurationSource
{
public IConfigurationProvider Build(IConfigurationBuilder builder)
{
return new MyConfigurationProvider();
}
}
MyConfigurationProvider:
class MyConfigurationProvider : ConfigurationProvider
{
// 使用 timer 创建一个线程来模拟配置发生变化
private readonly 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();
}
}
}
MyConfigurationBuilderExtensions:
public static class MyConfigurationBuilderExtensions
{
public static IConfigurationBuilder AddMyConfiguration(this IConfigurationBuilder builder)
{
builder.Add(new MyConfigurationSource());
return builder;
}
}
具体使用:
static void Main(string[] args)
{
var builder = new ConfigurationBuilder();
//builder.Add(new MyConfigurationSource());
//var configRoot = builder.Build();
//Console.WriteLine($"lastTIme:{configRoot["lastTIme"]}");
builder.AddMyConfiguration();
var configRoot = builder.Build();
ChangeToken.OnChange(() => configRoot.GetReloadToken(), () =>
{
Console.WriteLine($"lastTime:{configRoot["lastTime"]}");
});
Console.WriteLine("开始了");
Console.ReadKey();
}