Felix C
Felix C

Reputation: 1775

EntityFramework: Hold entity context per request via Unit of Work pattern

there are so much information available about unit of work pattern, but most of them are different.

I've learned that I should have for each request my own entity context. And that I should use Unit of Work pattern to reach this goal (from here. Entity Framework and Connection Pooling )

So I've implemented it exactly this way: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

But with only that implementation, I don't have one context per request, all requests are sharing the same context, right?

Then I found this link: http://www.mindscapehq.com/blog/index.php/2008/05/12/using-the-unit-of-work-per-request-pattern-in-aspnet-mvc/

But now I remember that I should not hold the context in session / HttpContext.Items variable. Is that right?

Where can I find a best implementation tutorial?

Upvotes: 0

Views: 3780

Answers (1)

Justin Helgerson
Justin Helgerson

Reputation: 25521

I follow the pattern given in your second link. You are not sharing a context across all requests with that pattern. Take a look at the sample code:

public class StudentController : Controller
{
    private IStudentRepository studentRepository;

    public StudentController()
    {
        this.studentRepository = new StudentRepository(new SchoolContext());
    }
}

For each request to the Student controller, a new instance of that class will be created. In the constructor of that class, it's creating a new repository instance with a new context. That means that the context will live only for the lifetime of that request.

Edit: Here's a little more clarification:

Maybe stepping backward in the process would help clarify. Start with a visitor hitting some action in your controller. ASP.NET is going to create an instance of your controller class. When it creates that instance, you will have a context in memory that will live for the duration of that request and no longer.

This works out just fine because you are performing work within your controller. Say for an example that a user asks to update their profile. How would you handle that with Entity Framework (EF)? First, you would use your repository and fetch their user record. Your context is now aware of that object. Then you take the data the visitor supplied (let's say they want to change their phone number) and update your EF object with the new value. The context is keeping track of those changes, so at the end of your action you can call .Save() and the proper update will be made to your database.

Upvotes: 2

Related Questions