Search code examples
dbcontext.net-framework-versionef-core-2.1

EF Core 2.1.1 DbContextPooling in .Net Framework 4.7.2 application


I can find a lot of articles on how to enable DbContextPooling in ASP Net Core through AddDbContextPool function. But what about .Net framework 4.7.2 when this is not available. How can I reuse the DbContext from the pool?

Thanks


Solution

  • AddDbContextPool sets up services in the dependency injection container to make it more efficient to get DbContext instances for each request.

    If you are not using ASP.NET Core, but your application follows a similar model (e.g. DbContext instances are needed to process Web or service requests) and the number of requests per second is very large, then my first recommendation would be to setup DI using Microsoft.Extensions.DependencyInjection and create DI scopes per request like ASP.NET Core does. Once you do that, you should be able to call AddDbContextPool the same way you would do in an ASP.NET Core application, and resolve your DbContext using DI with all the benefits of DbContext pooling.

    Besides that option, in theory you could do manually what AddDbContextPool achieves using DI.

    For example, first create a singleton pool of type DbContextPool. Then, for every instance of YourDbContext you need, get a lease using pool.Lease, and then get the context using lease.Context.

    You have to make sure that you dispose both the context and the lease when you are done using them.

    Caveat: this approach requires direct usage of low level APIs that are in internal namespaces and that therefore could change or disappear in any future minor or major release of EF Core.

    If your application doesn't work like that (for example, if it is not a web application or a web service that need to process large numbers of requests), then there is no advantage on using DbContext pooling.