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
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
Yeah I believe we currently have that kind of setup as well. But nothing solid yet
What would solid look like to you if this is not it? I'm curious what'd be a better solution
instead of the DbContextFactory use Middelware
Along these lines