Better way to dispose EF context in the controller

Solitario

New Member
I have a simple MagazineRepository class\[code\]public class MagazineRepository : IDisposable{ //EntityFramewokr context private DataBaseContext _context; public MagazineRepository() { _context = new DataBaseContext(); } public void Dispose() { if (_context != null) { _context.Dispose(); } GC.SuppressFinalize(this); }}\[/code\]And a simple controller:\[code\]public class MagazineController : Controller{ public ActionResult Index() { //Should to implement using to dispose using(MagazineRepository magazineRepository = new MagazineRepository()) { var magazine = magazineRepository.GetAll().ToList(); //Should use ToList() to avoid "Object has been disposed exception". return View(magazine); } } }\[/code\]What if i don't want to use "using" and "ToList()" in each Action? What if i will call Dispose() context method in the destructor of the controller? Something like this:\[code\]public class MagazineController : Controller{ MagazineRepository _magazineRepository; public MagazineController() { _magazineRepository= new MagazineRepository(); } ~MagazineRepository(); { if(_magazineRepository!=null) { _magazineRepository.Dispose(); } } public ActionResult Index() { var magazine = magazineRepository.GetAll(); return View(magazine); } }\[/code\]This code works, but i think it should be written in some other way. Context is able to live too long in last code example.So are there any patterns that can give me my db records without "using" and "ToList()" each time?
 
Back
Top