0
votes

Im using MassTransit Sagas. It starts when an incoming event(AccountCreatedInWebAppEvent) does some processing and will then publish another event (SagaAccountCreatedEvent)

I have a consumer that listens to SagaAccountCreatedEvent, but in the consumer the context.CorrelationId is null if I dont set it explicitly as in the example below (return new SagaAccountCreatedEvent() {...}). Shoulnt the correlationId be included without me having to insert it into the message, by the Saga-magic? (the same goes for publishing from a consumer to Saga-"handler")

InstanceState(i => i.CurrentState);
Event(() => AccountCreatedInWebAppEvent, e => e.CorrelateBy<int>(sagaState => sagaState.AccountId, context => context.Message.Account.AccountId)
                                                .SelectId(context => Guid.NewGuid()))

...

Initially(
    When(AccountCreatedInWebAppEvent)
        .Then(context =>
        {
            context.Instance.AccountId = context.Data.Account.AccountId;
            context.Instance.CreatedInWebApp = DateTime.Now; 
        })
        .TransitionTo(AccountCreatedSentOut)
        .Publish(context =>
        {
            return new SagaAccountCreatedEvent() { Account = context.Data.Account, CorrelationId = context.CorrelationId.Value };
        })

Consumer method

public async Task Consume(ConsumeContext context) {

//here context.correlationId is null

}

1

1 Answers

1
votes

Since your initial event is correlated by an int property, you are initializing the instance with SelectId(x => Guid.NewGuid()). To get that value when you publish the subsequent event, you should use context.Instance.CorrelationId as shown:

.Publish(context =>
    new SagaAccountCreatedEvent() 
    {
        Account = context.Data.Account,
        CorrelationId = context.Instance.CorrelationId
    })

The value you were using, context.CorrelationId is from the saga's consume context and is only present for events that are directly correlated by Guid using the CorrelationId.