﻿# Transactional Session with MongoDB Persistence

<!-- Version variant: mongots_6; default: [/nservicebus/transactional-session/persistences/mongodb.md](/nservicebus/transactional-session/persistences/mongodb.md) -->


In order to use the [transactional session feature](/nservicebus/transactional-session/index.md) with MongoDB persistence, add a reference to the `NServiceBus.Storage.MongoDB.TransactionalSession` NuGet package.

## Configuration

To enable the transactional session feature:

<!-- snippet: enabling-transactional-session-mongo -->

```cs
var persistence = config.UsePersistence<MongoPersistence>();
persistence.EnableTransactionalSession();
```

<!-- endsnippet -->

## Opening a session

To open a MongoDB transactional session:

<!-- snippet: open-transactional-session-mongo -->

```cs
using var childScope = serviceProvider.CreateScope();
var session = childScope.ServiceProvider.GetService<ITransactionalSession>();
await session.Open();

// use the session

await session.Commit();
```

<!-- endsnippet -->

## Transaction usage

Message and database operations made via the transactional session are committed together once the session is committed:

<!-- snippet: use-transactional-session-mongo -->

```cs
await session.Open();

// add messages to the transaction:
await session.Send(new MyMessage());

// access the database:
var mongoSession = session.SynchronizedStorageSession.MongoPersistenceSession();

await session.Commit();
```

<!-- endsnippet -->

See the [MongoDB persistence transactions documentation](/persistence/mongodb/index.md#transactions) for further details about using the MongoDB transaction.

> [!WARNING]
> In order to guarantee atomic consistency across message and database operations, the [outbox](/nservicebus/outbox/index.md) must be enabled. Otherwise `Commit` executes database modifications first and then messages are dispatched with best-effort.
