Component: NServiceBus
NuGet Package NServiceBus (5.x)
Standard support for version 5.x of NServiceBus has expired. For more information see our Support Policy.

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

public class MyHandler :
    public void Handle(MyMessage message)
        // 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 GenericHandler :
    static ILog log = LogManager.GetLogger<GenericHandler>();

    public void Handle(object message)
        log.Info($"Received a message of type {message.GetType().Name}.");
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, i.e. a pending Task or 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 mapped to a type using Assembly Qualified Name. This is the 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.

Unit testing

Unit testing handlers is supported by the NServiceBus.Testing library.

Related Articles

Last modified