开发者

What should UnityContainer.Teardown method do?

开发者 https://www.devze.com 2023-02-09 01:08 出处:网络
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:

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 life开发者_如何学Pythontime 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();
                }
            }
0

精彩评论

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

关注公众号