Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Modernization

Unit of Work Usage

This sample demonstrates how to implement a custom unit of work.

  1. Run the solution.
  2. Press s to send a message that succeeds.
  3. Press t to send a message that throws an exception.

Code walk-through

Immediate retries and delayed retries are disabled to avoid excessive error logging in the console.

CustomManageUnitOfWork

Logs both the start and end of the unit of work.

sealed 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

Registers the custom unit of work.

endpointConfiguration.RegisterComponents(
    registration: components => { components.AddTransient<CustomManageUnitOfWork>(); });

SuccessHandler

Logs when a message is successfully received.

sealed 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

Logs when a message is received, then throws an exception.

sealed 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