问题
I have an ASP.NET Core application that has a connection string key in the config file.
If its value is not correct (for example database name, ip address, etc), i wish to be able to re-register this dbcontext service with the new connection string after the user has changed it manually in the config file.
How to achieve this? Is this considered a bad practice?
Thank you.
回答1:
I see that you are using asp.net core.
Ideally you should not change your connection string when the application is running because it may cause a RESET of your web application (depending on the startup configurations and web server).
For answering your question, you can change configuration when application is running. ReloadOnChange parameter would be useful for you.
Below code sets reloadOnChange to true whenever there is change in appsettings.json configuration file.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
})
.UseStartup<Startup>();
Reference: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2
回答2:
With .NET Core, you need to configure your Startup OWIN app correctly for it to automatically reload your settings file.
In your startup class where you register the appsettings.json file, you need to tell it that it should reload on change. You pass it as a parameter. e.g
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", reloadOnChange: true)
Configuration = builder.Build();
}
Try something along the lines of the above code
To Elaborate on the above.
Changing setting files like this should ideally be managed through a deployment tool such as Octopus. This way you can define variables on the tool that will be used to replace app settings upon deployment. :)
来源:https://stackoverflow.com/questions/54124280/asp-net-core-re-registering-dbcontext-after-changing-connection-string