IManageUnitOfWork
is obsolete as of NServiceBus version 9. Use a pipeline behavior to manage a unit of work instead.
This sample demonstrates how to implement a custom unit of work.
In Versions 6 and above IManageUnitsOfWork
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.
- Run the solution.
- Press s to send a message that succeeds.
- 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");
}
}