1.14 配置框架:自定义配置数据源与配置中心方案.pdf

    MyConfigurationSource:

    1. class MyConfigurationSource : IConfigurationSource
    2. {
    3. public IConfigurationProvider Build(IConfigurationBuilder builder)
    4. {
    5. return new MyConfigurationProvider();
    6. }
    7. }

    MyConfigurationProvider:

    1. class MyConfigurationProvider : ConfigurationProvider
    2. {
    3. // 使用 timer 创建一个线程来模拟配置发生变化
    4. private readonly Timer _timer;
    5. public MyConfigurationProvider() : base()
    6. {
    7. _timer = new Timer();
    8. _timer.Elapsed += Timer_Elapsed;
    9. _timer.Interval = 3000;
    10. _timer.Start();
    11. }
    12. private void Timer_Elapsed(object sender, ElapsedEventArgs e)
    13. {
    14. Load(true);
    15. }
    16. public override void Load()
    17. {
    18. // 加载数据
    19. Load(false);
    20. }
    21. void Load(bool reload)
    22. {
    23. this.Data["lastTime"] = DateTime.Now.ToString();
    24. if (reload)
    25. {
    26. base.OnReload();
    27. }
    28. }
    29. }

    MyConfigurationBuilderExtensions:

    1. public static class MyConfigurationBuilderExtensions
    2. {
    3. public static IConfigurationBuilder AddMyConfiguration(this IConfigurationBuilder builder)
    4. {
    5. builder.Add(new MyConfigurationSource());
    6. return builder;
    7. }
    8. }

    具体使用:

    1. static void Main(string[] args)
    2. {
    3. var builder = new ConfigurationBuilder();
    4. //builder.Add(new MyConfigurationSource());
    5. //var configRoot = builder.Build();
    6. //Console.WriteLine($"lastTIme:{configRoot["lastTIme"]}");
    7. builder.AddMyConfiguration();
    8. var configRoot = builder.Build();
    9. ChangeToken.OnChange(() => configRoot.GetReloadToken(), () =>
    10. {
    11. Console.WriteLine($"lastTime:{configRoot["lastTime"]}");
    12. });
    13. Console.WriteLine("开始了");
    14. Console.ReadKey();
    15. }