2

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

Dale K
  • 25,246
  • 15
  • 42
  • 71
GPW
  • 2,528
  • 1
  • 10
  • 22
  • Don't think you are missing something. The underlying internal API also has no support for clearing the pool: https://github.com/dotnet/efcore/blob/main/src/EFCore/Internal/DbContextPool.cs – SynerCoder Jun 07 '23 at 10:00
  • Thanks, that was unfortunately the conclusion I came to but hoped I was missing something somewhere. – GPW Jun 07 '23 at 10:34
  • I don't think that by "changing the DB" the pool can contain more instances types. And you can't change them dynamically from what I know because your services are loaded only once when the api starts. – D A Jun 07 '23 at 11:05
  • Not changing the Context itself or the structure of the DB, just a different actual database - i.e. just changing the connection string but the "new" db has the same basic structure (though might need migrations run but I'm using Automatic migrations here, and that takes place during Context construction so works fine) – GPW Jun 07 '23 at 15:37

0 Answers0