Reputation: 10624
I have a unitofwork class, and I thought the Dispose() method will be called automatically but it is not.
public class UnitOfWork : IDisposable
{
private DBContext context = new DBContext();
private GenericRepository<Users> usersRepository;
public GenericRepository<Users> UsersRepository
{
get
{
if (this.usersRepository == null)
{
this.usersRepository = new GenericRepository<Users>(context);
}
return usersRepository;
}
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
Debug.WriteLine("This never be called :( ");
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
In many unitofwork and repository tutorial, I can not see any code to call Dispose() method. Do I need to call Dispose() method manually after all transaction be done?
I tried like this, but it doesn't work.
public class UserController : Controller
{
UnitOfWork unitofwork = new UnitOfWork();
~UserController() {
Debug.WriteLine("This is never called");
unitofwork.Dispose();
}
}
Upvotes: 2
Views: 2051
Reputation: 1
The class Controller is Disposable, and it is destroy at the end of each request. For more informations, you can just read this
public abstract class Controller : ControllerBase, [...] IDisposable, [...]
So you can override his Dispose method to destroy your own unitOfWork :
public class HomeController : Controller
{
private readonly UnitOfWork _unitOfWork = new UnitOfWork();
public ActionResult Index()
{
var homeViewModel = new HomeViewModel {Users = _unitOfWork.UserRepository.LastUsers()};
return View(homeViewModel);
}
protected override void Dispose(bool disposing)
{
_unitOfWork.Dispose();
base.Dispose(disposing);
}
}
Upvotes: 0
Reputation: 39807
If you want Dispose to be called automatically, you need to wrap in a using statement.
using(var uow = new UnitOfWork()){
..do stuff
}
At the end of the using statement, if an object has an IDisposable interface, the compiler will call the Dispose function in the generated Finally block. Else, without a using statement, then yes, you would need to call the dispose function manually.
In response to your edit...I am not sure what ~UserController() does (I have never seen that syntax? Are you trying to dispose in your constructor? Anyways, using the example below, you will see the Dispose method being called appropriately.
public class UserController : Controller
{
private UnitOfWork unitofwork;
public UserController(){
unitofwork = new UnitofWork();
}
public ActionResult DoStuff(){
var model = unitofwork.DoWork();
unitofwork.Dispose();
return View(model);
}
}
Upvotes: 4