我有我的控制器正在使用的这个基类:
public class BaseController : ApiController
{
protected JavaCertContext db = new JavaCertContext();
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
在我的几个控制器中,我还需要处理其他一些对象:
protected override void Dispose(bool disposing)
{
if (disposing && _userManager != null)
{
_userManager.Dispose();
_userManager = null;
}
base.Dispose(disposing);
}
在这些控制器中,我如何确保两者控制器Dispose和继承的继承的Dispose得到执行?
答案 0 :(得分:2)
这正是base.Dispose(disposing);
调用正在做的事情,即调用基类的dispose方法!
答案 1 :(得分:-2)
正确关注Dispose pattern。它将确保首先调用子处理,然后再处理父母的处置。
public class BaseController : ApiController
{
protected JavaCertContext db = new JavaCertContext();
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
public class ChildController : BaseController
{
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_userManager != null)
{
_userManager.Dispose();
_userManager = null;
}
}
base.Dispose(disposing);
}
}
public class ApiController
{
private volatile bool _isDiposed;
public void Dispose()
{
if (_isDiposed)
{
return;
}
Dispose(true);
_isDiposed = true;
}
protected virtual void Dispose(bool isDisposing)
{
if (isDisposing)
{
//Dispose stuff.
}
}
}
public class JavaCertContext
{
}