Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommended lifecycle for DbContext in ASP.NET Web API?

Consider an ASP.NET Web API 2 application, that provides fairly straightforward access to several DB tables using Entity Framework.

Which of the following options for object lifecycles would be best in terms of servicing the most concurrent requests?

  1. Instantiating a singleton DbContext to be used by all requests.
  2. Instantiating one DbContext for each incoming request.
  3. Instantiating one DbContext for each thread in the thread pool servicing incoming requests?
  4. Other?

Follow up question - What if I change the requirement to "requiring the least amount of DB server resources"? What would then be the best option?

like image 407
urig Avatar asked Aug 24 '14 15:08

urig


People also ask

What should be the lifetime of DbContext?

The lifetime of a DbContext begins when the instance is created and ends when the instance is disposed. A DbContext instance is designed to be used for a single unit-of-work. This means that the lifetime of a DbContext instance is usually very short.

Does DbContext need to be disposed?

Calling the Dispose method ensures that your Connection is closed. So, as long as you let DbContext manage your connections, feel free to ignore the Dispose method.

Is DbContext managed?

All . NET objects are managed and subject to garbage collection, this includes DbContext . In contrast, an unmanaged resource is usually something like a file handle that you need to close using low level winapi functions.


1 Answers

Based on a detailed reply to another question:

Options 1 and 3 in my question are completely invalid. The reason is that DbContext is not thread-safe and having multiple threads access will bring inconsistent data states and throw exceptions. Even in a "per thread" situation, ASP.NET Web API is likely to arbitrarily shift the handling of a single request between several threads.

Option 2 - Instantiating one DbContext for each incoming request - is the preferred way as it ensures only one thread at a time can access the DbContext.

like image 104
urig Avatar answered Oct 13 '22 23:10

urig