EventAggregator and Message Hierarchies

Jul 19, 2010 at 11:00 AM

I have a situation where I recieve / generate message objects dynamically. Each message object has a base class, e.g. BaseMessage.

public abstract class BaseMessage {

public class StatusMessage : BaseMessage {

And listeners listen to messages like this:

public class ViewModel : Screen, IHandle<StatusMessage> {

    public ViewModel(){

    public void Handle(StatusMessage msg){
now the problem is, I publish messages with the type of base class:

public void SomeEvent(){
    var msg = RecieveMessageDynamically() as BaseMessage;

The problem is that the message when handed to EventAggregator is of type BaseMessage and the listener can only handle messages of type StatusMessage to the event handler on listener class will not be called at all.

What I want is to be able to listen to derived messages, even when the message object passed to event aggregator is of a base type. Is this possible?

Jul 19, 2010 at 12:55 PM

You could use MakeGenericMethod to call the correct Publish method of the event aggregator. (http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod.aspx)

However, that implementation seems a bit dubious to me. Why would you aggregate all your messages somewhere other than the "event aggregator".

Do you have a specific reason why you would want to implement event handling in such a way?



Jul 19, 2010 at 1:08 PM

Thanks! Worked great!!

The reason behind it is that Message instances are received from the outside world (via network) and I just deserialize them and hand them to EventAggregator to send to responsible handlers.


Jul 19, 2010 at 1:19 PM

Makes sense.

Glad it worked.