Because messages are processed in a pipeline of handlers, you will, at times, have to execute code before the first handler and after the last handler. This is necessary for data stores that follow the unit of work pattern, such as NHibernate or RavenDB, where you need to create a database session before handling a message and then commit or rollback any changes at its completion. One method to accomplish this is by using a unit of work implementation. We will discuss another method when we cover the pipeline later in this chapter.
In order to define a unit of work implementation, you must first implement the NServiceBus.UnitOfWork.IManageUnitsOfWork
interface. Here, we have an example that will simply write messages to the console:
public class ConsoleUnitOfWork : IManageUnitsOfWork { public void Begin() { Console.WriteLine("---Begin message---"); } public void End(Exception ex = null) { Console.WriteLine("---End message---"); } }