MongoDB Persistence (Ryan Hoffman)

Project Hosting | Nuget: NServiceBus.Persistence.MongoDb (Version: 9.x) | License
This is a community run project. License and support are independent of Particular Software.
Target NServiceBus Version: 6.x

Uses MongoDB for storage.

Includes MongoDB persistence implementations for

Usage

To use MongoDB for persistence

Edit
endpointConfiguration.UsePersistence<MongoDbPersistence>();

Connection Settings

There are several ways to set the MongoDB Connection

Via Code

This enables resolving configuration setting at run-time.

Edit
var persistence = endpointConfiguration.UsePersistence<MongoDbPersistence>();
persistence.SetConnectionString("mongodb://localhost/databaseName");

Via an app.config Connection String

Edit
<connectionStrings>
  <add name="NServiceBus/Persistence/MongoDB"
      connectionString="mongodb://localhost/databaseName"/>
</connectionStrings>

The default connection string name can be override as follows:

Edit
var persistence = endpointConfiguration.UsePersistence<MongoDbPersistence>();
persistence.SetConnectionStringName("SharedConnectionString");

Saga definition guideline

For Sagas to work correctly the following needs to be enforced:

  • Saga Data should implement IContainSagaData.
  • Requires a property Version decorated with attribute [DocumentVersion].

For example:

Edit
public class OrderBillingSagaData :
    ContainSagaData
{
    public string OrderId { get; set; }

    [DocumentVersion]
    public int Version { get; set; }

    public bool Canceled { get; set; }
}

Dealing with concurrency

The key concurrency safeguards that sagas guarantee depend heavily on the underlying data store. The two specific cases that NServiceBus relies on the underling data store are concurrent access to non-existing saga instances and concurrent access to existing saga instances.

Concurrent access to non-existing saga instances

The persister uses Unique Indexes to ensure only one document can contain the unique data.

Concurrent access to existing saga instances

The persister uses a document versioning scheme built on top of findAndModify command to atomically update the existing persisted data only if it has not been changed since it was retrieved. Since the update is atomic, it will ensure that if there are multiple simultaneous updates to a saga, only one will succeed.

Samples

Related Articles


Last modified