Thursday 24 May 2012

Collections in NServiceBus 2.6 messages

I needed to create an NServiceBus message type (an implementation of IMessage) that contained a collection of sub items. My initial thought was to expose the collection as an IEnumerable in order to preserve encapsulation - I didn’t want client code to be able to modify the collection. Here’s an example:

public class MyMessage : IMessage
{
    public int SomeCode { get; set; }

    public IEnumerable<ListItem> Items { get; set; }
}
public class ListItem
{
    public string Key { get; set; }
    
    public string Message { get; set; } 
}

The problem was that the collection was turning up empty at the destination.

This turns out to be a feature of the NServiceBus XML serializer. This is described as follows:

“NServiceBus has its own custom XML serializer which is capable of handling both classes and interfaces as well as dictionaries and does not use the WCF DataContractSerializer. Binary serialization is done using the standard .net binary serializer.” - http://nservicebus.com/Performance.aspx

However, it seems the XML serializer isn’t as fully featured as other XML serializers but it is focussed on addressing problems relating to moving messages around quickly and efficiently.

In this case the solution was to change from using IEnumerable<T> to List<T>. Not too painful really.

public class MyMessage : IMessage
{
    public int SomeCode { get; set; }

    public List<ListItem> Items { get; set; }
}

Note that a number of serialization issues in NServiceBus – including this one - can be addressed by using the NServiceBus binary serializer.