In the tutorials for ASP.Net MVC, the LINQ to Entities code looks like:
public class MyController : Controller
{
private Models db;
public ActionResult Index()
{
db = new Models();
var foo = (from f in db.foo select f).ToList();
return View(foo);
}
}
I’m guessing this has something to do with thread safety/connection pooling, but I just wanted to know if anyone knew of any good reasons not to do it this way:
public class MyController : Controller
{
private readonly Models db = new Models();
public ActionResult Index()
{
var foo = (from f in db.foo select f).ToList();
return View(foo);
}
}
I just put together a tip that covers this in quite a lot of detail.
Your educated guess of threading is just one of the many reasons why it is generally better to construct/dispose of the Context in the method that needs it.
There are some situations where this rule of thumb doesn’t hold but they are pretty rare.
See this: Tip 18 – How to decide on a lifetime for your ObjectContext