MongoDB Persistence

Source
NuGet Package NServiceBus.Storage.MongoDB (2-pre)
Target NServiceBus Version: 7.x
This page targets a pre-release version and is subject to change prior to the final release.

Uses the MongoDB document database for storage.

Supported persistence types

Usage

Add a NuGet package reference to NServiceBus.Storage.MongoDB. Configure the endpoint to use the persistence through the following configuration API:

endpointConfiguration.UsePersistence<MongoPersistence>();

Customizing the connection

By default, a MongoClient is created that connects to mongodb://localhost:27017 and uses the endpoint name as its database name. This default connection is used for all the persisters.

Customize the server, port, and authentication database using the following configuration API:

var persistence = endpointConfiguration.UsePersistence<MongoPersistence>();
persistence.MongoClient(new MongoClient("SharedMongoUrl"));

Specify the database to use for NServiceBus documents using the following configuration API:

var persistence = endpointConfiguration.UsePersistence<MongoPersistence>();
persistence.DatabaseName("DatabaseName");

Multi-document transactions

Multi-document transactions are enabled and required by default. This allows the package to support updating multiple saga instances and commit them all atomically during message processing.

Disabling transactions

The following configuration API is available for compatibility with MongoDB server versions less than 4 or for use with sharded clusters:

var persistence = endpointConfiguration.UsePersistence<MongoPersistence>();
persistence.UseTransactions(false);

Shared transactions

NServiceBus supports sharing the same MongoDB session transaction between Saga persistence and business data. A single session transaction can be used to persist document updates for both concerns atomically.

To use the shared transaction in a message handler:

public Task Handle(MyMessage message, IMessageHandlerContext context)
{
    var collection = context.SynchronizedStorageSession.GetCollection<MyBusinessObject>("MyCollectionName");
    return collection.InsertOneAsync(new MyBusinessObject());
}

Samples

Related Articles


Last modified