Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Modernization
Samples

Custom Serializer for Data Bus

NuGet Package: NServiceBus.ClaimCheck (2-pre)
Target Version: NServiceBus 10.x
This page targets a pre-release version. Pre-releases are subject to change and samples are not guaranteed to be fully functional.
  1. Run the solution. Two console applications start.
  2. Find the Sender application by looking for the one with "Sender" in it's console title and press Enter to send a message. A message is sent that includes a DataBus property that is serialized using a custom serializer.
  3. The sample uses the FileShareDataBus. Open the solution folder in Windows Explorer and navigate to the \storage\ sub-folder. Each sub-folder within the \storage folder contains serialized data bus properties.

Code walk-through

This sample contains three projects:

  • Shared - A class library with messages and the custom data bus serializer.
  • Sender - A console application responsible for sending large messages.
  • Receiver - A console application responsible for receiving large messages from the sender.

Shared project

Look at the custom data bus serializer:

public class BsonClaimCheckSerializer :
    IClaimCheckSerializer
{
    public void Serialize(object databusProperty, Stream stream)
    {
        using (var writer = CreateNonClosingBinaryWriter(stream))
        using (var bsonWriter = new BsonDataWriter(writer))
        {
            serializer.Serialize(bsonWriter, databusProperty);
        }
    }

    public object Deserialize(Type propertyType, Stream stream)
    {
        using (var jsonReader = new BsonDataReader(stream))
        {
            return serializer.Deserialize(jsonReader, propertyType);
        }
    }

    static BinaryWriter CreateNonClosingBinaryWriter(Stream stream)
    {
        return new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true);
    }

    static JsonSerializer serializer = new JsonSerializer
    {
        TypeNameHandling = TypeNameHandling.All
    };

    public string ContentType => "application/bson";
}

The custom serializer implements IDataBusSerializer.

Sender project

The endpoint in the Sender project is configured to use the custom data bus serializer:

var claimCheck = endpointConfiguration.UseClaimCheck<FileShareClaimCheck, BsonClaimCheckSerializer>();
claimCheck.BasePath(SolutionDirectoryFinder.Find("storage"));

Receiver project

The endpoint in the Receiver project must be configured to use the same custom data bus serializer in order to read data bus properties sent by the Sender endpoint:

var claimCheck = endpointConfiguration.UseClaimCheck<FileShareClaimCheck, BsonClaimCheckSerializer>();
claimCheck.BasePath(SolutionDirectoryFinder.Find("storage"));

Related Articles