Complex saga finding logic

Component: NServiceBus | Nuget: NServiceBus (Version: 3.x)
Standard support for version 3.x of NServiceBus has expired. For more information see our Support Policy.

A saga can handle multiple messages. When NServiceBus receives a message that should be handled by a saga, it uses the configured mapping information to determine the correct saga instance that should handle the incoming message. In many cases the correlation logic is simple and can be specified using the provided mapping function, which is the recommended default approach. However, if the correlation logic is very complex it might be necessary to define a custom saga finder.

Custom Saga Finders are created by implementing IFindSagas.

Edit
public class MySagaFinder :
    IFindSagas<MySagaData>.Using<MyMessage>
{
    DbSessionProvider sessionProvider;

    // Inject the persistence specific session provide
    // For example purposes DbSessionProvider is a stub
    public MySagaFinder(DbSessionProvider sessionProvider)
    {
        this.sessionProvider = sessionProvider;
    }

    public MySagaData FindBy(MyMessage message)
    {
        // Use the injected sessionProvider to get a db session
        // For example purposes GetDbSession is a stub extension method
        var dbSession = sessionProvider.GetDbSession();
        return dbSession.GetSagaFromDB(message.SomeId, message.SomeData);
        // If a saga can't be found null should be returned
    }
}
In NServiceBus Versions 6 and above, and all integrations that target those versions, all extension points that return Task cannot return a null Task. These APIs must return an instance of a Task. For example either a pending Task, a CompletedTask, or be marked async. For extension points that return a Task<T> return the value directly (for async methods) or wrap the value in a Task.FromResult(value).

Many finders may exist for a a given saga or message type. If a saga can't be found and if the saga specifies that it is to be started for that message type, NServiceBus will know that a new saga instance is to be created.

When using custom saga finders users are expected to configure any additional indexes needed to handle concurrent access to saga instances properly using the tooling of the selected storage engine.

Samples

Related Articles

  • Saga Concurrency
    NServiceBus gives ACID semantics, using underlying storage so only one worker thread hitting a saga instance can commit.
  • Sagas
    NServiceBus uses event-driven architecture to include fault-tolerance and scalability in long-term business processes.

Last modified