AI agents: use the documentation index at llms.txt to locate machine-readable pages. This section is indexed by https://docs.particular.net/nservicebus/llms.txt. The markdown version of this page is served as plain text. An MCP server at /mcp serves the same content via the search_docs and read_doc tools; it is read-only and needs no credentials. Markdown versions of documentation pages are available by appending .md to the page URL. Directory URLs use index.md. They are served as text/plain because some retrieval backends reject text/markdown.

Complex saga finding logic

Component:
NServiceBus
NuGet Package:
NServiceBus 10.x

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.

public class MySagaFinder :
    ISagaFinder<MySagaData, MyMessage>
{
    public Task<MySagaData> FindBy(MyMessage message, ISynchronizedStorageSession storageSession, IReadOnlyContextBag context, CancellationToken cancellationToken)
    {
        // SynchronizedStorageSession will have a persistence specific extension method
        // For example GetDbSession is a stub extension method
        var dbSession = storageSession.GetDbSession();
        return dbSession.GetSagaFromDB(message.SomeId, message.SomeData);
        // If a saga can't be found Task.FromResult(null) should be returned
    }
}

Saga finders must be mapped to their related message:

protected override void ConfigureHowToFindSaga(SagaPropertyMapper<MySagaData> mapper)
{
    mapper.ConfigureFinderMapping<MyMessage, MySagaFinder>();
}

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

List of Samples

Related Articles

  • Saga concurrency
    NServiceBus ensures consistency between saga state and messaging.
  • Sagas
    Master NServiceBus sagas to coordinate distributed workflows and ensure reliable long-running processes.