-
Notifications
You must be signed in to change notification settings - Fork 26
Global Handlers
The Global Handlers are a fundamental concept in MicroBus that allows you to easily tackle cross cutting concerns within an application. A global handler implements the IDelegatingHandler
interface which requires you to implement the Handle method. This method takes the next Handler in the chain as well as the message as inputs and asynchronously returns a collection of results.
A typical implementation does the following:
- Process the incoming message.
- Call
next.Handle
to send the request to the inner handler. - The inner handler (asynchronously) returns a result.
- Process the result and return it to the caller.
Here's an example of what that looks like in code.
public class SomeHandler : IDelegatingHandler
{
public async Task<object> Handle(INextHandler next, object message)
{
// Process message
var result = await next.Handle(message);
// Process result
return result;
}
}
If an returns without calling the next handler, the message skips the remainder of the pipeline. This can be useful for an handlers that performs validation.
Another common use case for Global Handlers is for handling database transactions or the Unit of Work.
public class UnitOfWorkHandler : IDelegatingHandler
{
public async Task<object> Handle(INextHandler next, object message)
{
using (var transaction = unitOfWork.Begin()) {
return await next.Handle(message);
}
}
}
Now that we have all our Handlers declared it's time to register them to MicroBus. For this we use the generic RegisterGlobalHandler
method.
busBuilder.RegisterGlobalHandler<UnitOfWorkHandler>();
If multiple Global Handlers are registered they will execute in the order they appear. So the first Global Handler registered will be the first to process a message and the last to process the result.