I have a .NET Core 3.0 web application. I would like to change the connection string at run time once login is successful.
-
Does this answer your question? Dynamically change connection string in Asp.Net CoreSoumen Mukherjee– Soumen Mukherjee2020-02-01 02:16:02 +00:00Commented Feb 1, 2020 at 2:16
-
Possible duplicate of stackoverflow.com/questions/36816215/…Soumen Mukherjee– Soumen Mukherjee2020-02-01 02:16:18 +00:00Commented Feb 1, 2020 at 2:16
-
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– Merkle Groot2020-02-01 02:19:47 +00:00Commented Feb 1, 2020 at 2:19
Add a comment
|
2 Answers
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
}
Comments
After login you can save the connection string to session, cookie or your preferred storage then edit the DbContext as follow (I suppose that you have chosen session):
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; }
}