.net core 自定义配置数据源:低成本实现定制化配置方案 电脑版发表于:2020/6/30 16:45 ![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore") >#.net core 自定义配置数据源:低成本实现定制化配置方案 [TOC] <br/> 扩展步骤 ------------ <br/> - 实现IConfigurationSource - 实现IConfigurationProvider - 实现Addxxx扩展方法 <br/> 项目结构 ------------ ![](https://img.tnblog.net/arcimg/hb/7f81a0a10afa48609206d1cf6fe03af0.png) 简单示例 ------------ <br/> >###修改内容 <br/> ><font style="color:#2ecc71;font-weight:bold;">MyConfigurationProvider.cs</font> ```csharp class MyConfigurationProvider:ConfigurationProvider { //每3秒变更一次 Timer timer; public MyConfigurationProvider() : base() { timer = new Timer(); timer.Elapsed += Timer_Elapsed; timer.Interval = 3000; timer.Start(); } public override void Load() { //加载数据 Load(false); } private void Timer_Elapsed(object sender, ElapsedEventArgs e) { Load(true); } private void Load(bool v) { this.Data["lastTime"] = DateTime.Now.ToString(); if (v) { base.OnReload(); } } } ``` ><font style="color:#2ecc71;font-weight:bold;">MyConfigurationSource.cs</font> ```csharp class MyConfigurationSource : IConfigurationSource { public IConfigurationProvider Build(IConfigurationBuilder builder) { return new MyConfigurationProvider(); } } ``` ><font style="color:#2ecc71;font-weight:bold;">Program.cs</font> ```csharp var builder = new ConfigurationBuilder(); builder.Add(new MyConfigurationSource()); var configRoot = builder.Build(); Console.WriteLine($"lastTime:{configRoot["lastTime"]}"); Console.ReadKey(); ``` >###运行结果 ![运行结果](https://img.tnblog.net/arcimg/hb/d6aae3c57a1941058b0ba5106b9aeadc.png) 自定义扩展 ------------ >###修改内容 <br/> ><font style="color:#2ecc71;font-weight:bold;">MyConfigurationBuilderExtensions.cs</font> ```csharp namespace Microsoft.Extensions.Configuration { public static class MyConfigurationBuilderExtensions { public static IConfigurationBuilder AddMyConfiguration(this IConfigurationBuilder builder) { builder.Add(new MyConfigurationSource()); return builder; } } } ``` ><font style="color:#2ecc71;font-weight:bold;">Program.cs</font> ```csharp var builder = new ConfigurationBuilder(); builder.AddMyConfiguration(); var configRoot = builder.Build(); //监听 ChangeToken.OnChange(() => configRoot.GetReloadToken(), () => { Console.WriteLine($"lastTime:{configRoot["lastTime"]}"); }); Console.WriteLine($"开始了"); Console.ReadKey(); ``` >###运行结果 ![运行结果](https://img.tnblog.net/arcimg/hb/2039ffe2299748e8a99ba4887b194c1b.png)