I found a tutorial in microsoft asp.net website, that make an instance from context like this:
public class HomeController : Controller
{
private MoviesDBEntities _db = new MoviesDBEntities();
public ActionResult Index()
{
return View(_db.MovieSet.ToList());
}
...
}
this means each time controller instantiate, context will be instantiate too. but Here i was found that correct way to instantiate context is like this:
public class HomeController : Controller
{
public ActionResult Index()
{
using(MoviesDBEntities _db = new MoviesDBEntities()){
return View(_db.MovieSet.ToList());
}
}
...
}
so the question is, Which way is true? or is it important at all?
Generally, a class should not be responsible for instantiating its own dependencies.
The best thing to do is to pass the dependency into the constructor:-
This is called “Dependency Injection”, and it’s desireable because it reduces boilerplate code, and also allows you to supply other IMovieRepository implementations at runtime (e.g. if you’re unit testing).
ASP.NET MVC has a hook to allow you to do this (ControllerBuilder), but luckily you don’t need to roll your own, there are pre-made solutions out there. I recommend http://ninject.org/ because it’s very easy to set up.
That way your IoC Container (whatever is passing the dependency in) can instantiate only one context per HTTP request, and dispose of it at the end of the request.
Check out e.g. What is Inversion of Control?