Unit of Work Usage

Component: NServiceBus | Nuget: NServiceBus (Version: 6.x)

This sample shows how to create a custom Unit Of Work.

In Versions 6 and above IManageUnitsOfWorks does not have access to the incoming message context. If access to headers and/or message body is required instead implement a unit of work using behaviors instead.
  1. Run the solution.
  2. Press s to send a message that will succeed. Press t to send a message that will throw.

Code walk-through

Immediate Retries and Delayed Retries have been disabled to reduce the amount of error logged to the console.

CustomManageUnitOfWork

The Unit Of Work logs both the begin and end.

Edit
public class CustomManageUnitOfWork :
    IManageUnitsOfWork
{
    static ILog log = LogManager.GetLogger("CustomManageUnitOfWork");

    public Task Begin()
    {
        log.Info("Begin");
        return Task.CompletedTask;
    }

    public Task End(Exception exception = null)
    {
        if (exception == null)
        {
            log.Info("End Success");
        }
        else
        {
            log.Error("End Fail", exception);
        }
        return Task.CompletedTask;
    }
}

Component Registration

Edit
endpointConfiguration.RegisterComponents(
    registration: components =>
    {
        components.ConfigureComponent<CustomManageUnitOfWork>(DependencyLifecycle.InstancePerCall);
    });

SuccessHandler

The SuccessHandler logs the fact that a message has been received.

Edit
public class SuccessHandler :
    IHandleMessages<MessageThatWillSucceed>
{
    static ILog log = LogManager.GetLogger<SuccessHandler>();

    public Task Handle(MessageThatWillSucceed message, IMessageHandlerContext context)
    {
        log.Info("Received a MessageThatWillSucceed");
        return Task.CompletedTask;
    }
}

ThrowHandler

The ThrowHandler logs the fact that a message has been received, and then throws an exception

Edit
public class ThrowHandler :
    IHandleMessages<MessageThatWillThrow>
{
    static ILog log = LogManager.GetLogger<ThrowHandler>();

    public Task Handle(MessageThatWillThrow message, IMessageHandlerContext context)
    {
        log.Info("Received a MessageThatWillThrow");
        throw new Exception("Failed");
    }
}

Related Articles


Last modified