Detailed description of asp.net core reload application configuration

Time:2019-8-11

Asp.net core reload application configuration Intro

I put the configuration in the database or Redis. When the configuration needs to be modified, I need to modify the database directly. Then I call an interface to reload the application configuration. So I try to write an interface to reload the configuration at run time.

Configuration reload implementation

The interface for reloading the configuration is actually very simple.ConfigurationAs you can see from the source code, if you want to reload the application configuration, you need oneIConfigurationRootObject, andIConfigurationRootIn fact, it can be injected directly into the service.IConfigurationObjects, in servicesIConfigurationObjects are also implementedIConfigurationRootExamples of interfaces. Later, we can see the source code more clearly.

Look at the code that implements the reload configuration

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")// Here GetAppSetting is a custom extension method to get configuration information under the AppSettings node
      });
    }

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

Is it simple? Now let’s try it. You can refer to this sample project.

Because the default project configuration monitors whether the appsettings.json file is modified or not, and if it has been modified, it will reload again. Here I add a new file. Here I set it up.reloadOnChangebyfalseThe sample code is as follows:


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

The contents of abc.json’s document are as follows:


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

dotnet runStart the website and visit http://localhost:5000/api/configurations in the browser

Then we modify the abc. JSON file


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

After the modification and save, refresh the page just now, you can see the content just now, prove that the configuration has not been reloaded, and then try our reload configuration method.

Use postman or Fiddler or other tools you like to send a PUT request tohttp://localhost:5000/api/configurationsHere I use postman to call the PUT interface to reload the configuration

Return to 200, that is, the interface call is successful, refresh the page just now, you can see that the data on the page has changed, which also proves that our reloaded configuration of the interface is effective.

Source code parsing

Look atConfigurationBuilderWhat did you do in Build?ConfigurationBuilderSource code

You can see that the last one returned here is oneIConfigurationRootTarget, see againIConfigurationRootSource code

You can see thatIConfigurationRootDefine aReloadThis method will be from the followingProvidersTo reload the configuration, see here we know that we canIConfigurationOfReloadMethod to reload the configuration of the application, and then let’s look at itWebHost.CreateDefaultBuilder(args).Build()What did you do?
https://github.com/aspnet/AspNetCore/blob/master/src/DefaultBuilder/src/WebHost.cs

Here we can see why the appsettings. JSON file will automatically reload configuration, you can see that the last one returned.WebHostBuilderobject

Look at Asp.Net coreWebHostBuilderObjectBuildMethod https://github.com/aspnet/AspNetCore/blob/master/src/Hosting/src/WebHostBuilder.cs

stayBuildCommonServicesYou can see the code https://github.com/aspnet/AspNetCore/blob/master/src/Hosting/src/WebHostBuilder.cs.

We already know that.ConfigurationBuilderBuild returns aIConfigurationRootObject, and here injection is aIConfigurationObjects(IConfigurationRootRealizationIConfigurationInterface), so we can get it from dependency injectionIConfigurationObjects are treated directly asIConfigurationRootTo use, that’s why we get one directly.IConfigurationObject Directas IConfigurationRoot

Memo

That’s the end for now. I hope you can get something.~

Above is the detailed integration of asp. net core reloading application configuration introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message, Xiaobian will reply to you in time. Thank you very much for your support to developpaer.

Recommended Today

Implementation of PHP Facades

Example <?php class RealRoute{ public function get(){ Echo’Get me’; } } class Facade{ public static $resolvedInstance; public static $app; public static function __callStatic($method,$args){ $instance = static::getFacadeRoot(); if(!$instance){ throw new RuntimeException(‘A facade root has not been set.’); } return $instance->$method(…$args); } // Get the Facade root object public static function getFacadeRoot() { return static::resolveFacadeInstance(static::getFacadeAccessor()); } protected […]