我有一个 unitofwork 类,我认为 Dispose() 方法会被自动调用,但事实并非如此。
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);
}
}
在许多工作单元和存储库教程中,我看不到任何调用 Dispose() 方法的代码。所有事务完成后是否需要手动调用 Dispose() 方法?
我试过这样,但它不起作用。
public class UserController : Controller
{
UnitOfWork unitofwork = new UnitOfWork();
~UserController() {
Debug.WriteLine("This is never called");
unitofwork.Dispose();
}
}