Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

Newtonsoft BSON Serializer

NuGet Package: NServiceBus.Newtonsoft.Json (4.x)
Target Version: NServiceBus 9.x

This sample uses the Newtonsoft serializer NServiceBus.Newtonsoft.Json and configures it to use BSON.

Configuring to use NServiceBus.Newtonsoft.Json

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

var serialization = endpointConfiguration.UseSerialization<NewtonsoftJsonSerializer>();
serialization.ContentTypeKey("application/bson");
serialization.ReaderCreator(stream => new BsonDataReader(stream));
serialization.WriterCreator(stream => new BsonDataWriter(stream));

Diagnostic mutator

A helper that will write out the contents of any incoming message.

public class MessageBodyWriter(ILogger<MessageBodyWriter> logger) :
    IMutateIncomingTransportMessages
{
    public Task MutateIncoming(MutateIncomingTransportMessageContext context)
    {
        var bodyAsString = Encoding.UTF8
            .GetString(context.Body.ToArray());

        logger.LogInformation   ("Serialized Message Body:");
        logger.LogInformation(bodyAsString);

        return Task.CompletedTask;
    }
}

Register the mutator.

builder.Services.AddSingleton<MessageBodyWriter>();

// Then later get it from the service provider when needed
var serviceProvider = builder.Services.BuildServiceProvider();
var messageBodyWriter = serviceProvider.GetRequiredService<MessageBodyWriter>();
endpointConfiguration.RegisterMessageMutator(messageBodyWriter);

Sending a 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 messageSession.SendLocal(message);
Console.WriteLine("Order Sent");

Samples

Related Articles

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