Search code examples
asp.net-coremodel-view-controller.net-core

asp.net core how to change connection string at run time from entity framework (after login)


I have a .NET Core 3.0 web application. I would like to change the connection string at run time once login is successful.


Solution

  • IMO,you could not change the services.AddDbContext<T> at runtime.A workaround is that you add a DBContextFactory to create new dbcontext object when you login successfully.

    Refer to following steps:

    1.Create a DBContextFactory.cs

    public static class DbContextFactory
    {
        public static Dictionary<string, string> ConnectionStrings { get; set; }
    
        public static void SetConnectionString(Dictionary<string, string> connStrs)
        {
            ConnectionStrings = connStrs;
        }
    
        public static ApplicationDbContext Create(string connid)
        {
            if (!string.IsNullOrEmpty(connid))
            {
                var connStr = ConnectionStrings[connid];
                var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
                optionsBuilder.UseSqlServer(connStr);
                return new ApplicationDbContext(optionsBuilder.Options);
            }
            else
            {
                throw new ArgumentNullException("ConnectionId");
            }
        }
    }
    

    2.Intialize DbContextFactory in startup Configure

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            Dictionary<string, string> connStrs = new Dictionary<string, string>();
            connStrs.Add("DB1", "Your connection string 1");
            connStrs.Add("DB2", "Your connection string 2");
            DbContextFactory.SetConnectionString(connStrs);
            //other middlewares
        }
    

    3.Usage

    if(status)
    {
       var dbContext = DbContextFactory.Create("DB2");//get the dbcontext with connection string 2
    }