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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With