Handlers

Component: NServiceBus
NuGet Package NServiceBus (6.x)

To handle a message, write a class that implements IHandleMessages<T> where T is the message type:

public class MyAsyncHandler :
    IHandleMessages<MyMessage>
{
    public async Task Handle(MyMessage message, IMessageHandlerContext context)
    {
        // do something with the message data
    }
}

For scenarios that involve changing the application state via data access code in the handler, see accessing data.

To handle messages of all types:

  1. Set up the message convention to designate which classes are messages. This example uses a namespace match.
  2. Create a handler of type Object. This handler will be executed for all messages that are delivered to the queue for this endpoint.

Since this class is setup to handle type Object, every message arriving in the queue will trigger it.

public class GenericAsyncHandler :
    IHandleMessages<object>
{
    static ILog log = LogManager.GetLogger<GenericAsyncHandler>();

    public Task Handle(object message, IMessageHandlerContext context)
    {
        log.Info($"Received a message of type {message.GetType().Name}.");
        return SomeLibrary.SomeAsyncMethod(message);
    }
}
In NServiceBus Versions 6 and above, and all integrations that target those versions, all extension points that return Task cannot return a null Task. These APIs must return an instance of a Task. For example either a pending Task, a CompletedTask, or be marked async. For extension points that return a Task<T> return the value directly (for async methods) or wrap the value in a Task.FromResult(value).

If using the Request-Response or Full Duplex pattern, handlers will probably do the work it needs to do, such as updating a database or calling a web service, then creating and sending a response message. See How to Reply to a Message.

If handling a message in a publish-and-subscribe scenario, see How to Publish/Subscribe to a Message.

Mapping to name

Incoming messages will be to mapped to a type using Assembly Qualified Name. This is default behavior for sharing assemblies among endpoints. When a message cannot be mapped based on Assembly Qualified Name, the mapping will be attempted using FullName. The following is an example of how NServiceBus gets the type information.

var fqn = message.GetType().AssemblyQualifiedName;
var fallback = message.GetType().FullName;

Behavior when there is no handler for a message

Receiving a message for which there are no message handlers is considered an error and the received message will be forwarded to the configured error queue.

Related Articles


Last modified