C
C#2mo ago
Rowin ツ

Create a DbContext at build time, but change the connectionstring at runtime.

Hello, We are currently refactoring a few of our projects, and one of the problems we are having is wanting to switch databases in an SQL server. For example, we have our SQL server localhost with Database Test1, Test2, Test3, etc.... and we would like to change to which database the api is calling based on some other factors which is given by info from Redis. Now we can't find anything quite solid regarding achieving this without having to rebuild the whole DbContext. To keep in mind, all those databases are copies of eachother. But theyre are just meant for different people. Hence we think it would work by not having to re-create the DbContext.
4 Replies
Esa
Esa2mo ago
I think you should be able to use an IDbContextFactory to do this. Where you implement this contract you can create a method that takes an identifier as argument, and based on this identifier you can look up the correct connection string and use that to return the correct DbContext Mind you I haven't tried this, but just "thinking out loud" i could see this being worth investigating
Rowin ツ
Rowin ツ2mo ago
Yeah I believe we currently have that kind of setup as well. But nothing solid yet
Esa
Esa2mo ago
What would solid look like to you if this is not it? I'm curious what'd be a better solution
Rowin ツ
Rowin ツ2mo ago
instead of the DbContextFactory use Middelware
public class ConnectionStringMiddleware
{
private readonly RequestDelegate _next;
public ConnectionStringMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, IConnectionStringManager connectionStringManager)
{
if (context.Request.Headers.TryGetValue("New-Connection-String", out var newConnectionString))
{
connectionStringManager.SetConnectionString(newConnectionString);
}
await _next(context);
}
}
public class ConnectionStringMiddleware
{
private readonly RequestDelegate _next;
public ConnectionStringMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, IConnectionStringManager connectionStringManager)
{
if (context.Request.Headers.TryGetValue("New-Connection-String", out var newConnectionString))
{
connectionStringManager.SetConnectionString(newConnectionString);
}
await _next(context);
}
}
Along these lines