Search code examples
c#asp.net-coreentity-framework-core

How to refresh Entity Framework Core DbContext of ASP.NET Core project when connection string in web.config is changed?


I have an ASP.NET Core 8 project with Entity Framework Core. The connection string is taken from web.config in the root folder. While debugging in Visual Studio 2022, I enabled Hot Reload. I have figured out way to refresh DbContext when hot reload is triggered.

I use this code:

[assembly: System.Reflection.Metadata.MetadataUpdateHandler(typeof(HotReloadManager))]
namespace xxx
{
    internal static class HotReloadManager
    {
        public static void ClearCache(Type[]? types)
        {
            // Clear any caches if needed
        }

        public static void UpdateApplication(Type[]? types)
        { 
            using var context = new xxxDbContext();
            context.Database.EnsureCreated();
        }
    }
}

It works fine while hot reloading. DbContext is refreshed. Then the next thing is when I edit connection string in web.config, I find that this will not trigger hot reload. How can I achieve that?

New thought: If I want to use new connection string when DbContext is created, there is no necessary to involve hot reload.The only thing I need to do is to make sure OnConfiguring uses lates value from web.config file every time DbContext is created.

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            // make sure this connectionString value is always from fresh web.conifg file, not from ConfigurationManager cache
            string? connectionString = xxx;
            optionsBuilder.UseSqlServer(connectionString, providerOptions =>
            {
                providerOptions.CommandTimeout(300);
            });
        }

The methods have already been discussed in comments, which is to use OpenMappedExeConfiguration. But if website is with appSettings.json, then IOptionsSnapshot can help.


Solution

  • Have you tried using IOptions? Specifically IOptionsMonitor or IOptionsSnapshot. See below for additional info:

    IOptionsMonitor has an OnChange method that will be called when the underlying configuration source changes. Or you can use IOptionsSnapshot which might be better if DbContext is a scoped/transient service.

    This way you can also omit the HotReloadManager part.