Getting Started
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Previews
Samples

Transactional Session with MongoDB Persistence

NuGet Package: NServiceBus.Storage.MongoDB.TransactionalSession (3-pre)
This page targets a pre-release version. Pre-releases are subject to change and samples are not guaranteed to be fully functional.

In order to use the TransactionalSession feature with MongoDB persistence, add a reference to the NServiceBus.Storage.MongoDB.TransactionalSession NuGet package.

Configuration

To enable the TransactionalSession feature:

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

Opening a session

To open a MongoDB 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 mongoSession = session.SynchronizedStorageSession.MongoPersistenceSession();

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

See the MongoDB persistence transactions documentation for further details about using the MongoDB transaction.

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

Related Articles


Last modified