asp.net core application configuration reload

Original: ASP.NET application configuration reload Core

asp.net core application configuration reload

Intro

I put on a database or configure Redis, the need to modify the configuration when I want to directly modify the database, and then call an interface to application configuration reload, so he tried to reload the configuration of a write run-time interface.

Configuration reload achieve

Reload the configuration of the interface is actually very simple, look through the Configurationsource code to know, if you want to reload the application configuration requires a IConfigurationRoottarget, and IConfigurationRootin fact can be directly injected into the service to get IConfigurationthe object, service IConfigurationobject is also achieved IConfigurationRootinstance of an interface. Later we see the source code together that much is clear.

Look to achieve reload the configuration code

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace TestWebApplication.Controllers
{
    [Route("api/[controller]")]
    public class ConfigurationsController : Controller
    {
        private readonly IConfigurationRoot _configuration;

        public ConfigurationsController(IConfiguration configuration)
        {
            _configuration = configuration as IConfigurationRoot;
        }

        [HttpGet]
        public IActionResult Get()
        {
            return Ok(new
            {
                RootUser = _configuration.GetAppSetting("RootUser") // 这里 GetAppSetting 是一个自定义扩展方法,获取AppSettings 节点下的配置信息
            });
        }

        [HttpPut]
        public IActionResult Put()
        {
            _configuration.Reload();
            return Ok();
        }
    }
}

Lite :

        /// <summary>
        /// 重新加载系统配置
        /// </summary>
        /// <returns></returns>
        public IActionResult ReloadConfiguration()
        {
            var configurationRoot = HttpContext.RequestServices.GetService<IConfiguration>() as IConfigurationRoot;
            if (null == configurationRoot)
            {
                return BadRequest();
            }
            configurationRoot.Reload();
            return Ok();
        }

Is not it simple, let's try it, you can refer to this sample project

Since the default configuration of the project will monitor whether appsettings.json file modification, if you have modified will re-reload, and here I add a new file, set here reloadOnChangefor the falsesample code as follows:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(configBuilder =>
                {
                    configBuilder.AddJsonFile("abc.json", optional: true, reloadOnChange: false);
                })
                .UseStartup<Startup>();

abc.json the document reads as follows:

{
  "AppSettings": {
    "TestNumber": 12,
    "RootUser": "WeihanLi"
  }
}

dotnet runStart Web site, and then visit in the browser http: // localhost: 5000 / api / configurations

We then modify the file abc.json

{
  "AppSettings": {
    "TestNumber": 12,
    "RootUser": "WeihanLi 123"
  }
}

After modifying saved just refresh the page, you can see the content or just to prove that not reload the configuration, our next attempt to reload configuration

Use postman or fiddler or other tool you like to send a PUT request http://localhost:5000/api/configurations, and here I use the postman calls PUT interfaces reload the configuration

reload configuration

Ie the interface returns a 200 call was successful, just refresh the page, you can see data on the page has changed, which also proves that we reload the configuration interface in force.

Source resolve

Look ConfigurationBuilderat what to do when Build, ConfigurationBuilderSource

ConfigurationBuilder.Build()

Here you can see the last return is a IConfigurationRoottarget, and then look at IConfigurationRootthe source code

IConfigurationRoot

You can see IConfigurationRootthe definition of a Reloadmethod, this method from the following Providersreload the configuration, see where we can know IConfigurationthe Reloadway to re-load the configuration of the application, and then we look at WebHost.CreateDefaultBuilder(args).Build()what has been done
https: // github.com/aspnet/AspNetCore/blob/master/src/DefaultBuilder/src/WebHost.cs#L149

WebHost

Here we can see why appsettings.json will automatically reload the configuration file, you can see the last return an WebHostBuilderObject

Look Asp.Net core WebHostBuilderobject Buildmethod https://github.com/aspnet/AspNetCore/blob/master/src/Hosting/Hosting/src/WebHostBuilder.cs#L135

In BuildCommonServicesmay see this piece of code https://github.com/aspnet/AspNetCore/blob/master/src/Hosting/Hosting/src/WebHostBuilder.cs#L277

image.png

Above we already know that ConfigurationBuilderthe return Build after an IConfigurationRootobject, and this injection is a IConfigurationtarget ( IConfigurationRootimplement IConfigurationinterfaces), so we can get dependency injection from the IConfigurationobject directly as IConfigurationRootto use, which is why we get a direct IConfigurationobject directlyas IConfigurationRoot

Memo

To this end temporarily, I hope you can gain something -

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/11386810.html