I have a .NET Core 3.0 web application. I would like to change the connection string at run time once login is successful.
Asked
Active
Viewed 2,210 times
0
-
Does this answer your question? [Dynamically change connection string in Asp.Net Core](https://stackoverflow.com/questions/36816215/dynamically-change-connection-string-in-asp-net-core) – Soumen Mukherjee Feb 01 '20 at 02:16
-
Possible duplicate of https://stackoverflow.com/questions/36816215/dynamically-change-connection-string-in-asp-net-core – Soumen Mukherjee Feb 01 '20 at 02: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 Feb 01 '20 at 02:19
1 Answers
1
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
}
Ryan
- 17,241
- 8
- 29
- 43