This project is read-only.

Messenger

The DispatchedMessenger is an implementation of the Mediator pattern. It allows one actor to send a message to N number of disparate receivers (possible on different threads). The main benefit of it is to allow two ViewModels to interact with each other without having to have direct access to each other. Sacha Barber has written a very nice article on how to use the Mediator pattern in MVVM here.

Registering for Messages

All objects created by the activation service will be scanned for methods attributed with the MessageHandlerAttribute and BackgroundMessageHandlerAttribute. Below is an example of how to define a message handler.

    [MessageHandler]
    public void MessageHandler(SomeClass message)
    {
        // respond to message on UI thread
    }

    or 

    [BackgroundMessageHandler]
    public void BackgroundMessageHandler(SomeClass message)
    {
       // you are now on a background thread
    }

Sending a message

Sending a message is rather straight forward, you need to create a new message and call Send on the DispatchedMediator. Below is an example

         var message = new SomeClass();

         DispatchedMessenger.Instance.Send(message);

Messages

You can use any class as a message, but there is a base CallbackMessage class that you can inherit from if you want to do a message callback from the receiver to the sender. Below is an example of that

	public class SomeMessage : CallbackMessage<string>
	{
	    public SomeMessage(Action<string> callback) : base(callback)
	    {

	    }
	}

        Sender:

        var message = new SomeMessage(callbackMethod);
        
        DispatchedMessenger.Instance.Send(message);

        Receiver:
         
        [MessageHandler]
        public void MessageHandler(SomeMessage message)
        {
            message.Invoke("Hello from the receiver");
        }

Last edited Oct 31, 2012 at 2:04 PM by ipjohnson123, version 4

Comments

No comments yet.