Reputation: 63
I have a simple MagazineRepository class
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);
}
}
And a simple controller:
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);
}
}
}
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:
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);
}
}
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?
Upvotes: 1
Views: 4908
Reputation: 63
Someone answered my question, but then deleted it. Idea is to override Dispose method of the controller, because controller is disposing after action execution.
public class MyBaseController : Controller
{
protected IMyRepository _repository;
public RhotCMSController()
{
_repository = new MyRepository();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_repository != null)
{
_repository.Dispose();
}
}
base.Dispose(disposing);
}
}
public class MyController : MyBaseController
{
public ActionResult Index()
{
var entities = _repository.GetAll();
return View(entities);
}
}
Upvotes: 2