﻿# Transactional Session with SQL Persistence

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


In order to use the [transactional session feature](/nservicebus/transactional-session/index.md) with SQL Persistence, add a reference to the `NServiceBus.Persistence.Sql.TransactionalSession` NuGet package.

## Configuration

To enable the transactional session feature:

<!-- snippet: enabling-transactional-session-sqlp -->

```cs
var persistence = config.UsePersistence<SqlPersistence>();
persistence.EnableTransactionalSession();
```

<!-- endsnippet -->

## Opening a session

To open a SQL Persistence transactional session:

<!-- snippet: open-transactional-session-sqlp -->

```cs
using var childScope = serviceProvider.CreateScope();
var session = childScope.ServiceProvider.GetService<ITransactionalSession>();
await session.Open(new SqlPersistenceOpenSessionOptions());

// use the session

await session.Commit();
```

<!-- endsnippet -->

### Multi-tenancy support

The specific tenant ID that is used to construct the connection string is retrieved from message headers as configured in the [`MultiTenantConnectionBuilder`-method](/persistence/sql/multi-tenant.md).
This header needs to be set in the options so that the necessary information is available when storing operations and interacting with the outbox.

<!-- snippet: open-transactional-session-sqlp-multitenant -->

```cs
using var childScope = serviceProvider.CreateScope();
var session = childScope.ServiceProvider.GetService<ITransactionalSession>();
await session.Open(
        new SqlPersistenceOpenSessionOptions((
                     "MyTenantIdHeader", // Name of the header configured in this endpoint to carry the tenant ID
                     "TenantA"))); // The value of the tenant ID header

// 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-sqlp -->

```cs
await session.Open(new SqlPersistenceOpenSessionOptions());

// add messages to the transaction:
await session.Send(new MyMessage());

// access the database:
var sqlSession = session.SynchronizedStorageSession.SqlPersistenceSession();

await session.Commit();
```

<!-- endsnippet -->

See the [SQL shared session documentation](/persistence/sql/accessing-data.md) for further details about using the 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.
