MEF with Messaging issue

May 25, 2011 at 5:50 AM


I have a simple business application with 2 pages and 2 childWindows. To implement MVVM, I used MEF and the MVVMLight messaging mechanism. All is working well. My views are bound to their viewmodels and the viewmodels are communicating with each other using Messenger.Default.Register<...>.

My problem starts when I navigate out of a page and then come back to it. Then, the registered message actions happen twice. If i navigate into that page 3 times then the registered actions will happen 3 times. It's like that ViewModel instance MEF created is still there and everytime I navigate to the page it's creating a new instance of the ViewModel. How do I "destroy" that ViewModel instance? I was thinking, maybe, to go with Messenger.Default.Unregister(this) on a "NavigatedOut" event but that seems like a dirty solution. I don't fully understand MEF behind the scenes so I don't know how to go about it... any ideas?

Jun 2, 2011 at 11:04 AM


Registering and unregistering is important. In your particular scenario, the registration occurs multiple times which is the cause of your issue. Either you need to make sure that you register only once, or you need to cleanly unregister.

Even if an instance is garbage collected, it will not be removed immediately from memory. The GC kicks only when it needs to, in order to save performance. Because of this, unregistering properly when an instance is not used anymore is a good policy.

Does it make sense?



Jun 2, 2011 at 4:47 PM


Yes, it makes sense and that was my approace basically. In my case, I just fired an event on "NavigatingOut" of a page and I unregistered the ViewModel then.

Thanks for the reply!