user396491
user396491

Reputation: 941

EF Code First DBContext Lifetime for web applications

we are developing ASP.NET web application with cEF ode first. What/Where is the best possible place to create/dispose DBContext for a request? I have only a single context and am not using any DI containers. Currently i have multiple methods to call per request and each creates context of their own. How do i say, something like.. GetContextforRequest() and use it for the request and dispose it when request is processed?

Thanks in advance

Upvotes: 3

Views: 1135

Answers (1)

Jaimal Chohan
Jaimal Chohan

Reputation: 8645

What't your looking for in terms of having 1 context per request is a pretty good way to use contexts, in that you reduce the overhead of creating them. You can create new context on BeginRequest, and store it in HttpContext.Current.Items, and on EndRequest dispose of it.

You can then create a . GetContextforRequest() method to encapsulate the fetch from HttpContext.Current.Items

I would however suggest looking at using a DI container. most of them have helpers to aide with creating and disposing of objects per request.

Edit

The benefit of having a Context open for the duration of a Request is that you can take advantage of 1st level caching. This is where objects are cached for the lifetime of the Context. So say you have a table called User containing a bunch of Users, and you call context.Set().ToList() twice in the same request, the first call will fetch the data from the database, the second call will retrieve it from the 1st level cache.

Upvotes: 7

Related Questions