NServiceBus wrapping or not wrapping your messages

The configuration API has changed significantly. I updated the post.

I hope you all read the blog post about the serializer changes regarding raw xml embedding. In this blog post I want to show you an important interoperability feature which has been introduced in NServiceBus 4.0.0. You have now the possibility to define whether NServiceBus wrapps the serialized messages or not before passing it into the transport layer. Why is this important for interoperability?

NServiceBus has the notion of batching several logical messages into one physical message. A physical message is the message which is sent on the transport layer. You can batch commands or events together when you use one overload of the Send, Publish, Defer etc. method which takes an object array of messages as params. But what happens when you use that batching capability on the transport layer? Let us modify the example from the previous blog post:

    public class Server : IWantToRunWhenBusStartsAndStops
    {
        public const string Xml = ; // same as before

        public IBus Bus { get; set; }

        public void Start()
        {
            var firstXmlMessage = this.Bus.CreateInstance(m => m.XmlData = XDocument.Load(new StringReader(Xml)));
            var secondXmlMessage = this.Bus.CreateInstance(m => m.XmlData = XDocument.Load(new StringReader(Xml)));

            this.Bus.Send(firstXmlMessage, secondXmlMessage);
        }

        public void Stop()
        {
        }
    }

Now let’s see what is sent on the transport layer:

MultipleLogicalMessages

As we can see NServiceBus automatically wrapps the messages inside an Messages element. This happens even when you only send one message. In order to achieve maximum interoperability which other technologies we need to adjust two things in our example. First we need to make sure that we don’t use the batching capability in our system and thus always have one logical message equal to one physical message. Second we need a way to instruct NServiceBus to stop wrapping the message in the messages element. Only if we do this we get closer to natively interop based on the physical message body.

In NServiceBus 4.0.0 this is pretty easy. Just set the dontWrapSingleMessages flag to true either on the JSON or XML serializer. Only those two are supported because it wouldn’t make much sense with the other serializers because binary serialization is far from being interoperable itself.

This looks like the following in the endpoint configuration:

   Configure.Serialization.DontWrapSingleMessages()

Let us do a second look into the transport layer and of course this time by sending each message one by one:

OneMessageWithoutWrapping

From now on third party tools can just deserialize the body of the message.

About the author

Daniel Marbach

3 comments

By Daniel Marbach

Recent Posts