Skip to content

Cancellable Handlers

Daniel Little edited this page Feb 16, 2017 · 1 revision

MicroBus 3.5 added support for CancellationTokens though a number of new interfaces.

Alongside all the existing interfaces for IMicroBus and ICommandHandler there are now ICancelableMicroBus and ICancelableCommandHandler.

Messages sent using the new "Cancelable" interfaces allow you to specify a cancellation token what is passed down the entire pipeline.

ICancelableMicroBus
ICancelableMicroMediator

The only differences in these interfaces is an optional parameter containing the cancellation token. For example, the following line comes from the IMicroBus interface.

Task SendAsync(ICommand busCommand);

While this line is from the ICancelableMicroBus interface.

Task SendAsync(ICommand busCommand, CancellationToken cancellation = default(CancellationToken));

Any handler that implements the cancelable version of its interface will then be able to access the token and take the appropriate action if a cancellation occurs.

Again the only difference is the addition of the Cancellation Token.

public interface ICancelableDelegatingHandler
{
    Task<object> Handle(INextHandler next, object message, CancellationToken cancellation);
}

It's worth noting that you only need to use the cancellation interfaces if you need to access the token. The pipeline can contain any mixture of cancelable or traditional handlers.

public interface ICancelableCommandHandler<in TCommand>
    where TCommand : ICommand
{
    Task Handle(TCommand command, CancellationToken cancellation);
}

With regards to registration, assembly scanning will pick up these handlers and additional methods have been added for each Cancelable variant.

builder.RegisterCancelableCommandHandler<,>()
Clone this wiki locally