Although creating DbContext objects is really inexpensive, in really high performance scenarios it may be beneficial to switch to using Entity Frameworks DbContext pooling feature.
In this case EF Core will 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. Context pooling allows you to pay context setup costs only once at program startup.
There’s a simple benchmark on the Advanced Performance Topics page of the EF Core docs which I’ve adjusted slightly. It’s show significant time and memory allocation savings when using DbContext pooling….
Click on the image for a larger view in a new tab…
Even though we are dealing with small times here in high volume apps the timing and reduced memory allocations can definitely make a difference.
If you want to turn on DbContext pooling in Entity Framework you can do so with or without Dependency Injection.