本文意在通过ocelot 了解asp.net core 对配置文件的动态更新机制。
一 配置文件与对象绑定
UseOcelot方法调用时会执行配置文件对象创建,CreateConfiguration方法有个重要的对象 IOptionsMonitor<FileConfiguration> 通过
fileConfig.onchange 注册回调方法 更改存储库。实现对内存对象FileConfiguration 的更新。
public static async Task<IApplicationBuilder> UseOcelot(this IApplicationBuilder builder, OcelotPipelineConfiguration pipelineConfiguration) { var configuration = await CreateConfiguration(builder);
// ***
} private static async Task<IInternalConfiguration> CreateConfiguration(IApplicationBuilder builder) { // make configuration from file system? // earlier user needed to add ocelot files in startup configuration stuff, asp.net will map it to this var fileConfig = builder.ApplicationServices.GetService<IOptionsMonitor<FileConfiguration>>(); // now create the config // *** fileConfig.OnChange(async (config) => { var newInternalConfig = await internalConfigCreator.Create(config); internalConfigRepo.AddOrReplace(newInternalConfig.Data); }); }
先来看看IOptionsMonitor<T> 定义如下:
public interface IOptionsMonitor<out TOptions> { TOptions CurrentValue { get; } TOptions Get(string name); IDisposable OnChange(Action<TOptions, string> listener); }
IOptionsMonitor 从下面的服务注册可知 是OptionsMonitor<>
public static IServiceCollection AddOptions(this IServiceCollection services) {
// ***
services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptionsMonitor<>), typeof(OptionsMonitor<>)));return services; }
一 物理文件最终处理
public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((context, builder) => { builder.SetBasePath(context.HostingEnvironment.ContentRootPath) .AddJsonFile("Ocelot.json"); }) .UseUrls("http://localhost:6000") .UseStartup<Startup>() .Build();
webhost build的过程中都会绑定物理文件,如上的AddJsonFile。AddJsonFile的定义如下
public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange)
通过IFileProvider的实现,通过system.io对文件系统监控 实现最终的物理文件更改通知到上层。
二