Home > database >  Should I use AddDbContext or AddDbContextPool
Should I use AddDbContext or AddDbContextPool

Time:12-02

I have a web API that is using EF Core 5.0.12. I use the swagger web interface for debugging. I have noticed the first time I call a particular controller action in swagger it is slow (six seconds or more). Subsequent calls to that same action are much faster. I am not entirely sure how swagger calls get faster. In my Asp.Net Core SPA calls made to the API just seems slow every time.

Which got me thinking... Since, Asp.Net Core by default, disposes of the entity context after each call, would I benefit from using DbContext Pooling to avoid an EF query compile each time?

I am aware of a prior SO question here. But it seems a bit dated since I am using the latest stable versions of Ef Core and Asp.Net Core do the given answers still apply?

CodePudding user response:

The first call takes longer probably because of the connection to the database being initiated. After that, it uses Connection pooling to reuse the same connection for subsequent requests.

It's worth mentioning that DbContext uses an underlying connection object, but the fact that every request creates a new DbContext doesn't mean a new connection TCP handshake is made. Hence, there probably won't be any noticeable performance improvements just by replacing DbContext by DbContextPool.

  • Related