Search code examples
c#wpfcastle-windsorioc-container

Castle Windsor IoC - Memory leaks with Singleton/Transient references


I have a WPF application that is using IOC and the root composition pattern with constructor injection. Most of the parameters in the constructors of View Models are repositories. Some of the repositories are using a Singleton Lifestyle as they are caching stuff. All the View Models are Transient as I'd like the memory to be released as soon as the View is closed.

Having a reference to the singleton repository in the transient View Models is however keeping all of them in memory after they are no longer used, keeping the IOC container from releasing them.

Is there a pattern I can follow to release the classes when no longer used? I was thinking of implementing IDisposable on the ViewModels and just setting the repositories references to null but it doesn't sound right.


Solution

  • According to the blog of one of the committers of Castle Project:

    Must I release everything when using Windsor?

    Transient components are similar to pooled, because there’s no well known end to transient component’s lifetime, and Windsor will not know if you still want to use a component or not, unless you explicitly tell it (by calling Release). Since transient components are by definition non-shared Windsor will immediately destroy the component when you Release it.

    According to another one of his posts:

    Must Windsor track my components?

    Windsor by default will track objects that themselves have any decommission concerns, are pooled, or any of their dependencies is tracked.


    Now seriously – often people see that Windsor holds on to the components it creates as a memory leak (it often is, when used inappropriately which I’ll talk about in the next post), and they go – Windsor holding on to the objects causes memory leaks, so lets use the NoTrackingReleasePolicy and the problem is solved.

    Therefore we can say that Windsor will almost always keep a reference to your transient and pooled objects unless you explicitly release them.

    An elegant solution to your problem would be to write a custom LifestyleManager to release your view models when your application no longer needs them.