What is WeakReferenceMessenger? How to use it in .Net MAUI

Swetha vennapusa
Nerd For Tech
Published in
3 min readMar 2, 2023

--

MVVM architecture is based on the concept of a Loosely coupled or decoupled way which means that every component follows the strict separation of concern concept. Sometimes we want to communicate between these decoupled components then we use a publish-subscribe pattern.

The Publish-subscribe pattern is the messaging pattern in which publishers send messages without knowing any receivers, known as subscribers. Similarly, subscribers listen for specific messages, without knowing any publishers.

Before .NET 7 we were using Messaging Center publish-subscribe pattern. In .NET 7 Messaging Center has been deprecated and replaced with WeakReferenceMessenger in the CommunityToolkit.Mvvm.

WeakReferenceMessenger uses weak references internally, offering automatic memory management for recipients.WeakReferenceMessenger implements IMessenger. Types implementing IMessenger are responsible for maintaining links between recipients and their registered message types, with relative message handlers. Any object can be registered as a recipient for a given message type using a message handler, which will be invoked whenever the IMessenger instance is used to send a message of that type.

There are two ways to perform message registration:

  • Using a delegate acting as message handler(MessageHandler<TRecipient,TMessage>)
  • Using Interface IRecipient<TMessage>

--

--