views:

144

answers:

2

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.

A: 

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

Nicole Calinoiu
Oh, ok. Thanks!
Budda
A: 

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)

Budda
You shouldn't be registering the container with itself. See the post at http://unity.codeplex.com/Thread/View.aspx?ThreadId=46415#Post156036 for details.
Nicole Calinoiu
Not a lof of details except of: never register a container with itself. It's already done for you (new in Unity 1.2) so you don't gain anything, and you'll get a stack overflow at dispose time. Just add a dependency on IUnityContainer in your objects and it'll just work.But thats explain me a lot. :) Thank you!
Budda