We consider to use the Prism event aggregator for the purpose of reducing memory leaks due to event references.
-
Is this for itself a valid reason to use this pattern? The other benefits are not interesting for us now. We plan to use it between model components and not UI.
-
Our problem was that some developers forgot to unregister events. I saw that Prism has one flavour which uses weak references but it has limitations. The other flavour forces to explicitly Unsubscribe(), which again can be forgotten. So how is it better?
If this is your problem, switching to the Prism event aggregator (or, using any other implementation) won’t improve things.
Adding a new dependency with a new, non-trivial, usage pattern into a messy situation isn’t going to tidy it up at all.
What you need is to clean up your code.
Instead of new code libraries, I’d suggest looking into static analysis tools like fxCop (aka Code Analysis), Gendarme and NDepend. All of these are able to detect some situations where events are not unhooked or where IDisposable is not implemented properly.
Using static analysis, you can dispassionately identify code that needs cleanup. Throw in use of a memory profiler (like dotTrace Memory) and you’ll be able to find the worst offenders and clean them up promptly.
Update
In answer to the question in the comment below:
In can be difficult to make sure that all events are unsubscribed – but given the way that events are implemented (see CLR via C# for details), you can cheat a little by ensuring all event subscriptions are discarded.
Instead of
handle the event subscription yourself, like this:
Then, implement
IDisposableon your class, and in yourDispose()method setmFuBartonull, discarding the subscriptions. FxCop (and other tools) can then tell you if you are failing to Dispose of the class.