Reputation: 16841
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?
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
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:
You can also consume the OData service directly (for example with jQuery AJAX) or with a simpler library (datajs, JayData)
Upvotes: 0
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