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?
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With