Getting Started
Architecture
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

Transactional Session with NHibernate Persistence

NuGet Package: NServiceBus.NHibernate.TransactionalSession (9.x)
Target Version: NServiceBus 8.x

In order to use the transactional session feature with NHibernate Persistence, add a reference to the NServiceBus.NHibernate.TransactionalSession NuGet package.

Configuration

To enable the transactional session feature:

var persistence = config.UsePersistence<NHibernatePersistence>();
persistence.EnableTransactionalSession();

Opening a session

To open a NHibernate transactional session:

using var childScope = serviceProvider.CreateScope();
var session = childScope.ServiceProvider.GetService<ITransactionalSession>();
await session.Open()
    .ConfigureAwait(false);

// use the session

await session.Commit()
    .ConfigureAwait(false);

Transaction usage

Message and database operations made via the the transactional session are committed together once the session is committed:

await session.Open()
    .ConfigureAwait(false);

// add messages to the transaction:
await session.Send(new MyMessage())
    .ConfigureAwait(false);

// access the database:
var nhibernateSession = session.SynchronizedStorageSession.Session();

await session.Commit()
    .ConfigureAwait(false);

See the NHibernate shared session documentation for further details about using the transaction.

In order to guarantee atomic consistency across message and database operations, the outbox must be enabled. Otherwise Commit executes database modifications first and then messages are dispatched with best-effort.

Related Articles


Last modified