In my .net core mvc (2.2) application I have a configuration, configured from the database. How to reload the configuration from the controller, for example after changing some values in the database? I've tried something like this, but it does not work:
MyConfiguration.cs:
public class MyConfiguration
{
public string SmtpServer {get;set;}
}
Startup.cs:
public class Startup
{
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyConfiguration>(options => {
options.SmtpServer = Configuration["SmtpServer"];
});
// ...
services.AddSingleton<IConfiguration>(Configuration);
}
}
Program.cs:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost
.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
config.AddEFConfiguration(options => options.UseNpgsql("connection_string"));
config.AddCommandLine(args);
})
.UseStartup<Startup>();
}
Controller:
public class TestController : ControllerBase
{
private readonly IConfigurationRoot _configurationRoot;
public TestController(IConfiguration configurationRoot)
{
_configurationRoot = (IConfigurationRoot)configurationRoot;
}
[HttpGet]
public async Task<IActionResult> Index()
{
// some logic for updating values in the database
// Doesn't work
_configurationRoot.Reload();
return Ok();
}
}
IOptionsSnapshot
, you can get updated values per request. However, the config provider has to support reload. A database provider typically won't. – Lilylivered