Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

Custom serializers

Component: NServiceBus
NuGet Package: NServiceBus (8.1)

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(IReadOnlySettings 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(ReadOnlyMemory<byte> body, 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);
    }
}

Register the serializer

To use the customer serializer it must be registered as part of the endpoint configuration:

// register serializer additionally configuring settings
var serialization = endpointConfiguration.UseSerialization<MyCustomSerializerDefinition>();
serialization.Settings("settingsValue");