﻿# Complex saga finding logic

<!-- Version variant: core_7; default: [/nservicebus/sagas/saga-finding.md](/nservicebus/sagas/saga-finding.md) -->


A saga can handle multiple messages. When NServiceBus receives a message that should be handled by a saga, it uses the [configured mapping information](/nservicebus/sagas/index.md#correlating-messages-to-a-saga) 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](/nservicebus/sagas/index.md#correlating-messages-to-a-saga), 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`.

<!-- snippet: saga-finder -->

```cs
public class MySagaFinder :
    IFindSagas<MySagaData>.Using<MyMessage>
{
    public Task<MySagaData> FindBy(MyMessage message, SynchronizedStorageSession storageSession, ReadOnlyContextBag context)
    {
        // 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
    }
}
```

<!-- endsnippet -->



> [!NOTE]
> Cosmos DB persistence does not support custom saga finders. Use [message-property correlation](/nservicebus/sagas/message-correlation.md#message-property-expression) with a partition-aware mapping. For more information, see [Cosmos DB saga finding limitations](/persistence/cosmosdb/index.md#usage-saga-finding-limitations).

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.

> [!WARNING]
> When using custom saga finders, users are expected to configure any additional indexes needed to handle [concurrent access to saga instances](/nservicebus/sagas/concurrency.md) properly using the tooling of the selected storage engine. Due to this constraint, not all persisters will be able to support custom saga finders to the same degree.
>
> In instances where saga correlation requires data from more than one property on an incoming message, a better alternative is to use a [message property expression](/nservicebus/sagas/message-correlation.md#message-property-expression) instead of the overhead of a custom saga finder.
