Component: NServiceBus
NuGet NServiceBus (6.x)

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

public class MyAsyncHandler :
    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 for more details.

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 :
    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

NServiceBus will try to map incoming messages 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, NServiceBus will attempt to map to the FullName. The following is an example of how NServiceBus gets the type information.

string fqn = message.GetType().AssemblyQualifiedName;
string 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.

This behavior was slightly different in Version 3 where the message would only end up in the error queue if running in debug mode. If not in debug mode a Version 3 endpoint would log a warning but still consider the message successfully processed and therefore moving it to the configured error queue.

Related Articles

Last modified