Managing a unit of work via IManageUnitOfWork
is obsolete as of NServiceBus version 9. Instead, use a pipeline behavior to manage a unit of work.
This sample shows how to create 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 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.AddTransient<CustomManageUnitOfWork>();
});
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");
}
}