Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring

Unit of Work Usage

Component: NServiceBus
NuGet Package: NServiceBus (7.x)

This sample shows how to create a custom unit of work.

  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 number of errors logged to the console.

CustomManageUnitOfWork

The unit of work logs both the begining and end.

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

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

SuccessHandler

The SuccessHandler logs when a message has been received.

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 when a message has been received, then throws an exception

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