Skip to content
Mogens Heller Grabe edited this page Nov 14, 2023 · 6 revisions

Serialization with Rebus consists of transforming a Message into a TransportMessage and vice versa: turn a TransportMessage back into a Message.

Here, Message is an object that contains a headers dictionary and a message object, and TransportMessage represents the raw wire message, containing only headers (in the form of a Dictionary<string, string>) and a body (in the form of a byte[]).

As default (since Rebus 7), Rebus will JSON serialize messages using System.Text.Json (i.e. .NET's built-in JSON serializer). Rebus versions prior to 7 use Newtonsoft JSON.NET.

The choice of serializer

The choice of serializer affects a number of things, especially when an app needs to deserialize messages! How does it handle different versions of messages? When a field has been removed? When a field has been added? Etc.

This might be a reason why you will not be satisfied with the builtin JSON serializer, because it puts a limit on how much you can affect the serialization process. In this case, you might want to implement your own ISerializer, possibly using one of Rebus' existing serializers as inspiration, and then you're free to do whatever your serialization library will let you do.

Serialization options

If you want to select another serializer, bring in one of the several serialization packages - e.g. Rebus.Protobuf, Rebus.Hyperion, or Rebus.MsgPack and then do something like this:

services.AddRebus(
    configure => configure
        .(...)
        .Serialization(s => s.UseProtobuf())
);

The configuration extensions for all other Rebus serializer libraries follow the same pattern.

Customizing JSON serialization

If you just want to customize JSON serialization (e.g. by providing converters for specific value types), you can just use one of the overloads that accept JsonSerializerOptions (for System.Text.Json) or JsonSerializerSettings (for Newtonsoft JSON.NET). Here's how you can configure the serializers to name fields using camelCase - first System.Text.Json:

services.AddRebus(
    configure => configure
        .(...)
        .Serialization(s => s.UseSystemTextJson(new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        }))
);

and then Newtonsoft JSON.NET:

services.AddRebus(
    configure => configure
        .(...)
        .Serialization(s => s.UseNewtonsoftJson(new JsonSerializerSettings
        {
            ContractResolver = new DefaultContractResolver
            {
                NamingStrategy = new CamelCaseNamingStrategy
                {
                    OverrideSpecifiedNames = false
                }
            }
        }))
);
Clone this wiki locally