0
votes

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

2
Without seeing how your context is setup, it's hard to give a concrete answer. However, in most cases, you can just create a new database context and pass the connection string into the constructor. - Merkle Groot

2 Answers

2
votes

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
}
0
votes

i'm korean and Do not speak English well.

login after save session/cookie/DB UserConfig use, then DBContext edit

public class GroupwareContext : DbContext
{
    private readonly HttpContext _httpContext;
    public GroupwareContext(DbContextOptions<GroupwareContext> options, IHttpContextAccessor httpContextAccessor = null)
        : base(options)
    {
        _httpContext = httpContextAccessor?.HttpContext;
    }

    public GroupwareContext(DbContextOptions<GroupwareContext> options)
        : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (_httpContext != null) {
            if (_httpContext.Session.GetString("connectionString") != null)
            {
                var connectionString = (string)_httpContext.Session.GetString("connectionString");
                optionsBuilder.UseSqlServer(connectionString);
            }
        }

    }

    public DbSet<Account> Account { get; set; }
}