Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
637 views
Welcome To Ask or Share your Answers For Others

1 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...