Component: NServiceBus
NuGet Package NServiceBus (8-pre)
This page targets a pre-release version. Pre-releases are subject to change and samples are not guaranteed to be fully functional.

NServiceBus will take a message from the queue and hand it over to one or more message handlers. To create a message handler, 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.

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. Note that this might not be a recommended approach as writing a behavior is often a better solution.

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