Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should UnityContainer.Teardown method do?

I would like to explicitly "release" object instance resolved by Unity. I hoped the Teardown method should be used exactly for this so I tried something like this:

container.RegisterType(typeof(IMyType), typeof(MyType), 
    new MyLifetimeManager());
var obj = container.Resolve<IMyType>();
...
container.Teardown(obj);

MyLifetimeManager stores object instance in HttpContext.Current.Items. I expected that Teardown method will call RemoveValue on lifetime manager and release both MyType instance and lifetime manager instance. It doesn't work. First of all RemoveValue is not called and if I again call Resolve<IMyType> I will get previously resolved instance.

What should Teardown method do? How can I release object despite of his lifetime manager?

Edit:

If Teardown doesn't release the instance, who does? Who calls RemoveValue on lifetime manager?

like image 223
Ladislav Mrnka Avatar asked Feb 08 '11 13:02

Ladislav Mrnka


1 Answers

Unity TearDown doesn't do anything out of the box. You do not need to remove from HttpContext.Current.Items as it will be cleared automatically at the end of the request. What you may want to do is call Dispose on any IDisposable object stored there. You would do this from EndRequest in Global.asax:

foreach (var item in HttpContext.Current.Items.Values)
            {
                var disposableItem = item as IDisposable;

                if (disposableItem != null)
                {
                    disposableItem.Dispose();
                }
            }
like image 70
Paul Hiles Avatar answered Sep 19 '22 13:09

Paul Hiles