I'm using .NET 7 and EF Core 7 to access SQL Server.
I have basically an API application which can receive requests and uses EF for DB stuff.
It potentially will serve thousands of requests per minute depending on the specific deployment, and uses DBContext pooling to help performance/memory usage, set up by a call like this in the startup code:
services.AddDBContextPool<MyContext>((provder, opts) =>
{
var settings = provider.GetService<ISettings>();
opts.UseSqlServer(
settings.ConnectionString,
sqlOpts => sqlOpts.CommandTimeout(settings.CommandTimeout));
}
This works fine, but the reason for dynamically fetching connection settings each time is that I'd like to make them able to be changed at runtime, so if they do get "switched" to point to a different database then it will start creating contexts associated with the new database instead of the old one.
This gives a problem when using Context Pooling because a request might end up with a pre-existing context which is pointing at the "old" DB.
So what I would like to be able to do is simply to clear the pool when the connection string is changed, but I cannot see a good way to do this. I was looking into using a custom IDbContextFactory
and using .AddPooledDbContextFactory
instead but this doesn't appear to give me what I want either....
Really I just need some sort of way to access the underlying pool and either clear it out on command, or simply "invalidate" all contexts which are currently "warmed up".
Am I missing something, or is there another approach which might work?
Thanks in advance