Unity 中的递归和 Dispose 模式实现
我的类继承自UnityContainer(来自Unity 2.0),这里是源代码:
public class UnityManager : UnityContainer
{
private UnityManager()
{
_context = new MyDataClassesDataContext();
// ...
}
protected override void Dispose(bool disposing)
{
if ( disposing )
{
_context.Dispose();
}
base.Dispose(disposing);
}
private readonly CMCoreDataClassesDataContext _context;
}
当为UnityManager类的实例调用Dispose方法时,它会陷入递归......为什么?据我所知,base.Dispose 应该只调用基类的 Dispose 方法......不是吗?谁回调了UnityManager的Dispose(bool)?如何预防呢?
谢谢。
My class is inherited from UnityContainer (from Unity 2.0), here is source code:
public class UnityManager : UnityContainer
{
private UnityManager()
{
_context = new MyDataClassesDataContext();
// ...
}
protected override void Dispose(bool disposing)
{
if ( disposing )
{
_context.Dispose();
}
base.Dispose(disposing);
}
private readonly CMCoreDataClassesDataContext _context;
}
When Dispose method is called for the instance of UnityManager class it drop into recursion... Why? As far as I know base.Dispose should call the Dispose method of base class only... isn't it? Who call back the Dispose(bool) of UnityManager? How to prevent that?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
感谢妮可,我找到了一个理由...谢谢。
但这种情况下如何处置容器呢?如果为 UnityManager 实例调用“Dispose”,则 base.Dispose(true) 将再次调用 Dispose.... 并再次(递归将开始)。
为了解决这个问题,我添加了额外的私有变量 bool _bDispose:
这是 Bill Wagner 在“Effective C#”中建议的“Dispose”模式实现(如果我没有任何错误)
Thanks to Nicole I've found a reason... thanks.
But how to dispose container in this case? In case of call 'Dispose' for instance of UnityManager the base.Dispose(true)will call Dispose again.... and again (recursion will start).
To workaround this I've added additional private variable bool _bDisposed:
This is a "Dispose" pattern implementation suggested by Bill Wagner in "Effective C#" (If I didn't any mistake)
您是否已在容器中注册了 UnityManager 实例?如果是的话,当容器被丢弃时,它将被容器丢弃。
Have you registered your UnityManager instance in the container? If so, it will be disposed by the container when the container is disposed.