(十四)配置的热更新
这一节演示下配置的热更新,即不用重启网站,更改配置文件的信息,网站也能同步更改。还是继续沿用OptionsBindSample
- 实现也比较简单,改下Index.cshtml
-
1 @using Microsoft.Extensions.Options 2 @inject IOptionsSnapshot<OptionsBindSample.Class> ClassAccesser //原来的IOptions改成IOptionsSnapshot 3 @{ 4 ViewData["Title"] = "Index"; 5 } 6 7 <h2>Index</h2> 8 9 <div> 10 @foreach(var stu in ClassAccesser.Value.Students) 11 { 12 <span>Name:@stu.Name</span> 13 <span>Age:@stu.Age</span> 14 15 } 16 </div>
实现原理看https://github.com/aspnet/MetaPackages/blob/dev/src/Microsoft.AspNetCore/WebHost.cs,162行
- 如果要禁用配置热更新
- Program.cs
-
1 public static void Main(string[] args) 2 { 3 BuildWebHost(args).Run(); 4 } 5 6 /// <summary> 7 /// 启动的时候默认会读取appsettings.json文件 8 /// </summary> 9 /// <param name="args"></param> 10 /// <returns></returns> 11 public static IWebHost BuildWebHost(string[] args) => 12 WebHost.CreateDefaultBuilder(args)//只要配置文件名称是appsettings.json。CreateDefaultBuilder会读取appsettings.json 13 .ConfigureAppConfiguration((config)=> { 14 config.AddJsonFile("appsettings.json",false,true);//这里第三个参数reloadOnChange为false就是禁止热更新,否则就是允许热更新 15 }) 16 .UseStartup<Startup>() 17 .Build();