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
public class MySagaFinder :
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
Task cannot return a null Task. These APIs must return an instance of a Task, i.e. a pending Task or 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
Many finders may exist for 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. 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 instead of the overhead of a custom saga finder.