Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manage ADO.NET Entity Framework ObjectContext in ASP.NET MVC

I'm using ADO.NET EF in an MVC application. I'm considering putting the ObjectContext inside HttpContext.Current so that all logic in the same request can access to it without having to open/destroy each time. However, I'm really sure if it's a good way to manage ObjectContext instances. I have 2 questions regarding this need:

  1. As HttpContext.Current property is backed by a thread-local field and ASP.NET uses threads from pool to handle requests, is it possible that an ObjectContext instance put into HttpContext.Current by a request will be visible to a subsequent request running on the same thread from the pool?

  2. How do you think ObjectContext should be managed in ASP.NET MVC to both avoid lots of opening/disposing and prevent race conditions?

like image 700
Buu Nguyen Avatar asked Dec 16 '08 06:12

Buu Nguyen


2 Answers

Use the Repository pattern. Override Controller.Dispose to dispose the Repository, which, in turn, disposes the DataContext.

like image 81
Craig Stuntz Avatar answered Nov 04 '22 19:11

Craig Stuntz


I would use an IoC container like StructureMap, Autofac, Windosor, etc.

like image 40
Todd Smith Avatar answered Nov 04 '22 17:11

Todd Smith