urig
urig

Reputation: 16841

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?

Upvotes: 6

Views: 3647

Answers (2)

JotaBe
JotaBe

Reputation: 39045

Apart from not being thread safe, DbContexts should not be long lived. So you must use 2. (Or even one DbContext instance for each Db operation).

If your "fairly straightforward access to several DB tables" is really straightforward, I'd recommend you to use OData, and some advance js client, like breeze.js.

Please, see this sites:

  • ASP.NET Web API OData this exposes the data as a simple REST service
  • breeze.js this library provides advanced js functionality, similar to that offered by a DbContext, but on the browser side: syntax similar to LINQ, local (browser) data caching...

You can also consume the OData service directly (for example with jQuery AJAX) or with a simpler library (datajs, JayData)

Upvotes: 0

urig
urig

Reputation: 16841

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.

Upvotes: 2

Related Questions