Unity resolved objects not getting garbage collected

Feb 3, 2011 at 11:09 AM

We are building a LOB application using SL4,PRISM and MVVM. I noticed very lately that my App is not releasing any memory. It Starts around 150MB and grows to 1 GB+ very fast if i switch b/w pages. Our design involves 3 modules each having a Controller class(Unity singleton) which listens for events and injects views into the appropriate region. So this is whats happening in those controllers when an event is fired to inject a view.

var v = Container.resolve<view>() 
var vm = Container.resolve<viewmodel>() 
.datacontext = vm; 

so 100 calls for this view will exceute this 100 times. And in addviewregion method, i'm removing all existing views before adding the new one. And after seeing the memory problem, i set both view & viewmodel to null in addviewtoregion method for all the views nedd to be removed. still memry consumption is same. Is Unity ContainerControllled... objects(my controllers) holding referrences to these objects?



The following behavior illustrates the title of this discussion:

WeakReference ref1 = new WeakReference(Container.Resolve<Footer>());
WeakReference ref2 = new WeakReference(new Footer());
bool isRef1Alive = ref1.IsAlive;
bool isRef2Alive = ref2.IsAlive;

Footer is a UserControl and here first one returns true whereas the second one returns false. Why is this behavior different? Does Container holds any reference to the item it resolves? BTW, i dont have any interfaces for this view. I added

Container.RegisterType<Footer, Footer>();

in the Bootstrapper(ConfigureContainer method). still same result.


Feb 14, 2011 at 1:06 AM

Yes, the container holds a reference to the object that was resolved from it if it was registered using ContainerControlledLifetimeManager

However, I haven't worked on an application using the MVVM model so my question is, does your object really need to be registered as a singleton object?  You might also try to look at the ExternallyControlledLifetimeManager which also returns the same instance of the object everytime you resolve for the object but the container won't hold a strong reference to it so the garbage collector can dispose it even while the container is still in use.


Sarah Urmeneta
Global Technologies and Solutions
Avanade, Inc.