views:

102

answers:

1

I would like to use a base message class like:

[Serializable]
public abstract class MessageBase : IMessage
{
    public Guid MessageID { get; private set; }
    public DateTime UtcDateTime { get; private set; }

    protected MessageBase()
    {
        UtcDateTime = DateTime.UtcNow;
        MessageID = Guid.NewGuid();
    }

    public override string ToString()
    {
        return string.Format("{0} MessageID={1}, UtcDate={2}", GetType().FullName, MessageID, UtcDateTime);
    }
}

New messages will be created by subclassing from this base class. Here is the problem I observed. When I publish a message, I see that the message id and datetime is different when it is handled.

What am I missing?

+2  A: 

I know you want to declare MessageID and UtcDateTime with private setters so that someone down the line can't change it, but in doing so, you prevent the serializer from re-applying those values when the message is reconstructed at the receiver.

What is happening is that the serializer instantiates a new instance of your message type, and your two properties are initialized to UtcNow and NewGuid(), and then aren't overridden from the message. This is why they appear different.

If you remove the private keyword from the property declaration, you should get the behavior you are expecting.

However, instead of baking your own tracking mechanisms like this, you should at least (assuming you have injected an IBus into your handler) take a look at Bus.CurrentMessageContext, which contains an "Id" property for the message being handled (string, not Guid) and a Headers collection. I'm not 100% certain, but if you inspect the headers there is probably some indication of the original send time in there.

David
Thanks David, your answer is spot on.
developer