What is Unity's equivalent of Windsor's Release method

Dec 7, 2012 at 1:22 PM

I have some unmanaged resources in classes I'm injecting into controllers that I need to dispose once the controller is disposed (otherwise I'll have memory leak). I have looked at IUnityContainer and did not find a Release (or similar) method that allow me to do that.

After some trial and error (and reading), it seems to me that Unity do not keep track of what is going on about the types it creates. This is way different from Windsor, where I can call Release and the entire object graph will be release. This is actually one of the points of having a container in the first place (object lifecycle management). I should not need to call Dispose directly the container should be able to do that for me in the proper order/objects.

So, my question is, how can I tell Unity that an object is no longer needed and should be disposed?

If there is no way of doing that, is there a way to change the lifecycle to per web request?

Dec 7, 2012 at 2:32 PM

Unity does not dispose of object graphs out of the box.  There is a Teardown method but that does not actually do anything out of the box.  Here is a good article along with code to do implement an extension to do this: Unity Extension For Disposing Build Trees On TearDown.

A common approach to a per web request lifecycle is to use child containers along with a Hierarchical lifetime manager.  This is what Unity.Mvc3 does'; see Introducing The Unity.Mvc3 NuGet Package To Reconcile MVC3, Unity and IDisposable for a description.

Randy Levy
Enterprise Library support engineer