Core重新注册dbcontext

Core重新注册dbcontext

本文介绍了更改连接字符串后,ASP.NET Core重新注册dbcontext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET Core应用程序,该应用程序在配置文件中具有连接字符串键.

I have an ASP.NET Core application that has a connection string key in the config file.

如果其值不正确(例如,数据库名称,IP地址等),那么我希望能够在用户在配置文件中手动更改它之后,使用新的连接字符串重新注册该dbcontext服务.

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?

谢谢.

推荐答案

我看到您正在使用asp.net核心.

I see that you are using asp.net core.

理想情况下,您不应在应用程序运行时更改连接字符串,因为它可能导致Web应用程序重置(取决于启动配置和Web服务器).

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).

为回答您的问题,您可以在应用程序运行时更改配置.ReloadOnChange参数对您很有用.

For answering your question, you can change configuration when application is running. ReloadOnChange parameter would be useful for you.

以下代码在appsettings.json配置文件发生更改时将reloadOnChange设置为true.

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>();

参考: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2

这篇关于更改连接字符串后,ASP.NET Core重新注册dbcontext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:18