Upgrading NServiceBus handlers to async/await
This post is part of a series describing the improvements in NServiceBus 6.0.
In order to support the async/await keywords in NServiceBus 6.0, we had to make the first ever breaking change to the message handler API. We realize that this is a big change, and it’s not one that we made lightly. The move to async/await required that the Handle
method signature return a Task
instead of void
. At the same time, we replaced IBus
with context-specific parameters to make it clearer which messaging operations are available from within a message handler.
So now instead of this:
private IBus bus;
public void Handle(MyMessage message)
{
// Your code here
}
We now have this:
public async Task Handle(MyMessage message, IMessageHandlerContext context)
{
// Your code here
}
In order to make the conversion process as easy as possible, we’ve prepared a screencast that demonstrates how to convert a message handler from the previous syntax to the async-enabled API in NServiceBus 6.0.
Take a look:
Of course, we realize that it isn’t always fun to pause and replay a video, so here are the same basic instructions in text form:
- Because the definition for
IHandleMessages<T>
has changed in NServiceBus 6.0, reimplement the interface so you can see the new method signature. - Visual Studio will place the new
Handle
method at the bottom of the class. Copy the method signature, and then remove the empty method. - Paste the method signature from the clipboard over your existing method signature so that it’s replaced with the new signature.
- Notice the new
context
method parameter, which replaces theIBus
instance. - To ease replacement, rename the current
IBus
instance frombus
(or whatever you use in your project) tocontext
. Because of this refactoring, you won’t need to replace every reference. - After renaming, remove the old
IBus
instance from the class. - Add the
async
keyword to the handler method so that you havepublic async Task Handle
. - All of the messaging operations on the
context
parameter are async methods. Add theawait
keyword to all these calls, and addConfigureAwait(false)
to the end. As an example,this.context.Publish(new MyEvent());
becomesawait context.Publish(new MyEvent()).ConfigureAwait(false);
.
Keep in mind that NServiceBus 6.0 is fully backwards compatible with NServiceBus 5.x, meaning an older endpoint can send messages to a 6.0 endpoint and vice versa. This means you can take your time and convert one endpoint at a time with minimal risk.
So now that you’ve learned how to update your handlers, pick an endpoint to convert over and get started with NServiceBus 6.0 right away. For even more complete guidance, check out Asynchronous Handlers in our documentation.