How do you register a behavior to execute after the "Handle" method in NServiceBus 6?

779 Views Asked by At

I have an Endpoint with a Handle method. I would like to do something immediately before and immediately following Handle. I was able to get the step working before by imolementing LogCommandEntryBehavior : Behavior<IIncomingLogicalMessageContext>. What needs to be implemented to happen immediately following Handle?

1

There are 1 best solutions below

1
On BEST ANSWER

In NServiceBus Version 6, the pipeline consists of a series of Stages, each one nested inside the previous like a set of Russian Dolls. For an incoming message, the stages are (in order):

  • ITransportReceiveContext,
  • IIncomingPhysicalMessageContext,
  • IIncomingLogicalMessageContext, and
  • IInvokeHandlerContext

When you create a behavior within a stage, you get passed a delegate called next(). When you call next() you execute the next behavior in the pipeline (which may move the pipeline to the next stage). The call to next() returns a Task which indicates when this inner part of the pipeline is done.

That gives you the opportunity to invoke your code before moving on to the next stage, and invoke more code after the next stage has been completed like this:

public class LogCommandEntryBehavior : Behavior<IIncomingLogicalMessageContext>
{
    public override async Task Invoke(IIncomingLogicalMessageContext context, Func<Task> next)
    {
        // custom logic before calling the next step in the pipeline.

        await next().ConfigureAwait(false);

        // custom logic after all inner steps in the pipeline completed.
    }
}

If you want to log information about the handling of a message, I recommend looking at the IInvokeHandlerContext stage. It contains information about how the message was handled and will be called once for every handler that is invoked (in cases where you have multiple). If you don't need info at that level then IIncomingLogicalMessageContext is probably all you need.

You can read more about the Version 6 pipeline in the Particular Docs site: