What should UnityContainer.Teardown method do?

廉价感情. 提交于 2019-12-01 16:19:28

问题


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?


回答1:


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();
                }
            }


来源:https://stackoverflow.com/questions/4933388/what-should-unitycontainer-teardown-method-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!