Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AddDbContext or AddDbContextPool

For Asp.net Core apps, which one do we have to use? AddDbContext or AddDbContextPool? According to EF Core documentation, AddDbContextPool provides high performance but the default Asp.net Core project templates use AddDbContext.

like image 844
In Vladimir Putin We Trust Avatar asked Jan 25 '18 13:01

In Vladimir Putin We Trust


People also ask

What is difference between AddDbContext and AddDbContextPool?

The difference between AddDbContext() and AddDbContextPool() methods is, AddDbContextPool() method provides DbContext pooling. With DbContext pooling, an instance from the DbContext pool is provided if available, rather than creating a new instance.

When would you use EF6 vs EF core?

Keep using EF6 if the data access code is stable and not likely to evolve or need new features. Port to EF Core if the data access code is evolving or if the app needs new features only available in EF Core. Porting to EF Core is also often done for performance.

Does EF core use connection pooling?

For these cases, EF Core can pool your context instances: when you dispose your context, EF Core resets its state and stores it in an internal pool; when a new instance is next requested, that pooled instance is returned instead of setting up a new one.

What is dbContextOptions?

The dbContextOptions carries the configuration information needed to configure the DbContext. The dbContextOptions can also be configured using the OnConfiguring method. This method gets the DbContextOptionsBuilder as its argument. It is then used to create the dbContextOptions.


1 Answers

The answer is here (under "DbContext pooling"): https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-2.0#dbcontext-pooling

DbContext is not thread-safe. So you cannot reuse the same DbContext object for multiple queries at the same time (weird things happen). The usual solution for this has been to just create a new DbContext object each time you need one. That's what AddDbContext does.

However, there is nothing wrong with reusing a DbContext object after a previous query has already completed. That's what AddDbContextPool does. It keeps multiple DbContext objects alive and gives you an unused one rather than creating a new one each time.

Which one you use is up to you. Both will work. Pooling has some performance gains. However the documentation warns that if you use any private properties in your DbContext class that should not be shared between queries, then you should not use it. I imagine that's pretty rare though, so pooling should be appropriate in most cases.

like image 192
Gabriel Luci Avatar answered Sep 20 '22 10:09

Gabriel Luci