Unit of Work

Component: NServiceBus | Nuget: NServiceBus (Version: 3.x)
Standard support for version 3.x of NServiceBus has expired. For more information see our Support Policy.

Implementing custom units of work

A unit of work allows for shared code, that wraps handlers, to be reused in a way that doesn't pollute the individual handler code. For example, committing NHibernate transactions, or calling SaveChanges on the RavenDB session.

IManageUnitsOfWork

To create a unit of work, implement the IManageUnitsOfWork interface.

Edit
public class MyUnitOfWork :
    IManageUnitsOfWork
{
    public void Begin()
    {
        // Do custom work here
    }

    public void End(Exception ex = null)
    {
        // Do custom work here
    }
}

The semantics are that Begin() is called when the transport messages enters the pipeline. A transport message can consist of multiple application messages. This allows any setup that is required.

The End() method is called when the processing is complete. If there is an exception, it is passed into the method.

This gives a way to perform different actions depending on the outcome of the message(s).

Registering a unit of work

After implementing a IManageUnitsOfWork, it needs to be registered:

Edit
var configureComponents = configuration.Configurer;
configureComponents.ConfigureComponent<MyUnitOfWork>(DependencyLifecycle.InstancePerUnitOfWork);

Samples


Last modified