Unit of Work Usage

Component: NServiceBus | Nuget: NServiceBus (Version: 5.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 void Begin()
    {
        log.Info("Begin");
    }

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

Component Registration

Edit
busConfiguration.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 void Handle(MessageThatWillSucceed message)
    {
        log.Info("Received a MessageThatWillSucceed");
    }
}

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 void Handle(MessageThatWillThrow message)
    {
        log.Info("Received a MessageThatWillThrow");
        throw new Exception("Failed");
    }
}

Related Articles


Last modified