Message Queues with different message types

Julian Gold picture Julian Gold · May 29, 2012 · Viewed 7.8k times · Source

I'm investigating Microsoft Message Queues for doing inter-process cross-network messaging. But when I receive a message, I don't know a priori what type of object I'm getting, so the code

queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(Wibble) });

can't be applied before I get the message because I don't know if it's a Wibble. So how do I receive different message types?

Answer

Damien_The_Unbeliever picture Damien_The_Unbeliever · May 29, 2012

You're already using the constructor overload for XmlMessageFormatter that accepts an array of types. So just add all of the types that you're expecting to receive into that array, rather than just one type.

queue.Formatter = new XmlMessageFormatter(new Type[] {
    typeof(Wibble),
    typeof(Fleem),
    typeof(Boo)
});

From TargetTypes:

The instance serialized in the message body must comply with one of the schemas represented in the type array. When you read the message using the Receive method, the method creates an object of the type that corresponds to the schema identified and reads the message body into it.

(Emphasis added)