I’ve been using castle.windsor on a fairly large WPF project recently, and have encountered a particular issue – namely injecting something as lifestyle transient.
These days most of us .net developers aren’t worrying too much about memory leaks – the garbage collector has been doing a pretty good job cleaning things up for us, and all has been good. This particular project uses dependency injection extensively, and leverages castle.windsor for this. We have also been using windsor interceptors to add generic logging and error handling – this is an important thing to note as it means that we really need to inject EVERYTHING – otherwise, we lose our standard logging interception.
When injecting our view models (MVVM) with windsor we realised that the default lifestyle of singleton was not going to work, so we switched to lifestyle transient (i.e. a new instance every time). This works…..but creates a memory leak!!
Why does this happen
This happens because the garbage collector will only clean things up when there are no memory references back to that object – this makes sense – if the garbage collector starts cleaning up objects we still using we’d be pretty annoyed. But the fact is that when windsor tracks objects, it retains references to everything it injects – so even if the location it was injected is disposed of, windsor will still hold a reference – and therefore, the object will not get garbage collected.
We couldn’t expect windsor to (magically) know when we’ve finished using the object – so how do we resolve this?
The Typed Factory Facility
Windsor provides us with a facility to register a typed factory, that gives us the hooks we need to remove the item from its container (and therefore allow the garbage collector to tidy it up). I wont go into the details of how to implement a windsor typed factory as I think its written up pretty well on the windsor website.