Custom serializers

Component: NServiceBus
NuGet Package NServiceBus (7-pre)
This page targets a pre-release version and is subject to change prior to the final release.

Create a custom serializer

A custom serializer needs to implement IMessageSerializer interface:

class MyCustomSerializerDefinition :
    SerializationDefinition
{
    public const string Key = "MyCustomSerializer.Settings";

    public override Func<IMessageMapper, IMessageSerializer> Configure(ReadOnlySettings settings)
    {
        return mapper =>
        {
            var value = settings.GetOrDefault<string>(Key);
            return new MyCustomSerializer(value);
        };
    }
}

class MyCustomSerializer :
    IMessageSerializer
{
    public MyCustomSerializer(string settingsValue)
    {
        // Add code initializing serializer on the basis of settingsValue
    }

    public void Serialize(object message, Stream stream)
    {
        // Add code to serialize message
        throw new NotImplementedException();
    }

    public object[] Deserialize(Stream stream, IList<Type> messageTypes = null)
    {
        // Add code to deserialize message
        throw new NotImplementedException();
    }

    public string ContentType
    {
        get { throw new NotImplementedException(); }
    }
}

static class MyCustomSerializerConfigurationExtensions
{
    public static void Settings(this SerializationExtensions<MyCustomSerializerDefinition> config, string value)
    {
        var settingsHolder = config.GetSettings();
        settingsHolder.Set(MyCustomSerializerDefinition.Key, value);
    }
}

In order to see sample implementations, refer to the community run serializers.

Register the serializer

Register the serializer:

// register serializer additionally configuring settings
var serialization = endpointConfiguration.UseSerialization<MyCustomSerializerDefinition>();
serialization.Settings("settingsValue");
When using multiple deserializers make sure that there's only one type registered per given ContentType.

Last modified