Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

XML Serializer sample

Component: Xml Serializer
NuGet Package: NServiceBus (9.x)

This sample demonstrates the built-in NServiceBus XML serializer.

Configuring to use XML

var endpointConfiguration = new EndpointConfiguration("Samples.Serialization.Xml");

endpointConfiguration.UseSerialization<XmlSerializer>();

// register the mutator so the the message on the wire is written
endpointConfiguration.RegisterMessageMutator(new MessageBodyWriter());

Diagnostic mutator

A helper that will log the contents of any incoming message:

public class MessageBodyWriter :
    IMutateIncomingTransportMessages
{
    readonly static ILog log = LogManager.GetLogger<MessageBodyWriter>();

    public Task MutateIncoming(MutateIncomingTransportMessageContext context)
    {
        var bodyAsString = Encoding.UTF8.GetString(context.Body.ToArray());

        log.Info("Serialized Message Body:");
        log.Info(bodyAsString);

        return Task.CompletedTask;
    }
}

Sending the message

var message = new CreateOrder
{
    OrderId = 9,
    Date = DateTime.Now,
    CustomerId = 12,
    OrderItems = new List<OrderItem>
            {
                new OrderItem
                {
                    ItemId = 6,
                    Quantity = 2
                },
                new OrderItem
                {
                    ItemId = 5,
                    Quantity = 4
                },
            }
};

await endpointInstance.SendLocal(message);

Output

<?xml version="1.0" ?>
<CreateOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.net/XmlSample">
 <OrderId>9</OrderId>
 <Date>2015-09-15T13:33:28.7186624+10:00</Date>
 <CustomerId>12</CustomerId>
 <OrderItems>
  <OrderItem>
   <ItemId>6</ItemId>
   <Quantity>2</Quantity>
  </OrderItem>
  <OrderItem>
   <ItemId>5</ItemId>
   <Quantity>4</Quantity>
  </OrderItem>
 </OrderItems>
</CreateOrder>

Related Articles

  • Serialization
    .NET messaging systems require serialization and deserialization of objects sent/received over transports. NServiceBus achieves this using serializers.
  • XML Serializer
    A custom XML serializer.