LogoLogo
  • Home Page
  • Use Cases
  • How-To
    • Installation
    • First steps
    • Handling Messages
    • Publishing messages
    • Logging levels
Powered by GitBook

Links

  • Repository
On this page
  • Starting a Saga
  • Handling messages
  • Stopping a Saga
  1. How-To

Handling Messages

PreviousFirst stepsNextPublishing messages

Last updated 1 month ago

Starting a Saga

In order to start a Saga, we need to tell OpenSleigh which message type can be used as "initiator". To do that, we need to add the interface to the Saga and implement it:

public class MyAwesomeSaga :
    Saga,
    IStartedBy<StartMyAwesomeSaga>
{
    public async ValueTask HandleAsync(IMessageContext<StartMyAwesomeSaga> context, CancellationToken cancellationToken = default)
    {
        _logger.LogInformation($"starting saga '{context.Message.CorrelationId}'...");
    }
}

Messages are simple POCO classes (or records), implementing the interface:

public record StartMyAwesomeSaga() : IMessage { }

Handling messages

In order to handle more message types, it is necessary to add and implement the interface on the Saga:

public class MyAwesomeSaga :
    Saga,
    IStartedBy<StartMyAwesomeSaga>,
    IHandleMessage<MyAwesomeSagaCompleted>,
{
    // code omitted for brevity

    public async ValueTask HandleAsync(IMessageContext<MyAwesomeSagaCompleted> context, CancellationToken cancellationToken = default)
    {
        _logger.LogInformation($"saga '{context.Message.CorrelationId}' completed!");
    }
}

Stopping a Saga

A Saga can be marked as completed by calling the MarkAsCompleted() on its state:

public class MyAwesomeSaga :
    Saga,
    IStartedBy<StartMyAwesomeSaga>,
    IHandleMessage<MyAwesomeSagaCompleted>,
{
    // code omitted for brevity

    public async ValueTask HandleAsync(IMessageContext<MyAwesomeSagaCompleted> context, CancellationToken cancellationToken = default)
    {
        this.Context.MarkAsCompleted();
    }
}

This step is completely optional but signals Opensleigh to stop sending messages to that Saga instance.

IStartedBy<>
IMessage
IHandleMessage<>