Raw messaging using NServiceBus

Source
NuGet Package NServiceBus.Raw (1.x) | License
This is a community-maintained project. License and support are independent of Particular Software.
Target NServiceBus Version: 6.x
Standard support for version 6.x of NServiceBus has expired. For more information see our Support Policy.

NServiceBus.Raw allows sending and receiving of raw messages using the NServiceBus transport infrastructure. It is flexible in terms of message manipulation, and is a good fit for integration with third-party systems, as well as building gateways and bridges.

Configuration

Configuration of raw endpoints is similar to the standard NServiceBus endpoint configuration:

var senderConfig = RawEndpointConfiguration.Create(
    endpointName: "EndpointName",
    onMessage: OnMessage,
    poisonMessageQueue: "error");
senderConfig.UseTransport<MsmqTransport>();

var sender = await RawEndpoint.Start(senderConfig)
    .ConfigureAwait(false);

Sending

The following code sends a message to another endpoint:

var body = Serialize();
var headers = new Dictionary<string, string>
{
    ["SomeHeader"] = "SomeValue"
};
var request = new OutgoingMessage(
    messageId: Guid.NewGuid().ToString(),
    headers: headers,
    body: body);

var operation = new TransportOperation(
    request,
    new UnicastAddressTag("Receiver"));

await sender.Dispatch(
        outgoingMessages: new TransportOperations(operation),
        transaction: new TransportTransaction(),
        context: new ContextBag())
    .ConfigureAwait(false);

Receiving

The following code implements the callback invoked when a message arrives at a raw endpoint:

static Task OnMessage(MessageContext context, IDispatchMessages dispatcher)
{
    var message = Deserialize(context.Body);

    Console.WriteLine(message);
    // Can use dispatcher to send messages from here

    return Task.CompletedTask;
}

Notice that the method gets a dispatcher object which can be used to send messages. The TransportTransaction object can be passed from the receiving context to the dispatcher, in order to ensure transactions span both send and receive operations. It's important to ensure that the underlying transport infrastructure supports the SendsAtomicWithReceive transaction mode when using this option.


Last modified