AddDbContext or AddDbContextPool

asp.net-core asp.net-core-2.0 entity-framework-core

Question

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.

1
34
1/25/2018 1:03:40 PM

Accepted Answer

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.

58
10/11/2018 3:36:37 PM

Popular Answer

There are the following differences between AddDbContext and AddDbContextPool

  1. We can use either AddDbContext() or AddDbContextPool() method to register our application specific DbContext class with the ASP.NET Core dependency injection system.
  2. The difference between AddDbContext() and AddDbContextPool() methods is, AddDbContextPool() method provides DbContext pooling.
  3. With DbContext pooling, an instance from the DbContext pool is provided if available, rather than creating a new instance.
  4. DbContext pooling is conceptually similar to how connection pooling works in ADO.NET. From a performance standpoint AddDbContextPool() method is better over AddDbContext() method.
  5. AddDbContextPool() method is introduced in ASP.NET Core 2.0. So if you are using ASP.NET Core 2.0 or later use AddDbContextPool() method over AddDbContext() method.


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow