开发者

Recursion in Unity and Dispose pattern implementation

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 Uni开发者_JS百科tyManager 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.


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:

    protected override void Dispose(bool disposing)
    {
        if (_bDisposed)
            return;

        if ( disposing )
        {
            _context.Dispose();
        }
        _bDisposed = true;

        base.Dispose(disposing);
    }

    private bool _bDisposed;

This is a "Dispose" pattern implementation suggested by Bill Wagner in "Effective C#" (If I didn't any mistake)


Have you registered your UnityManager instance in the container? If so, it will be disposed by the container when the container is disposed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜