Is it possible to to correlate a message in MassTransit Saga that is not based on a ID?

920 views Asked by At

Is it possible to match an incoming message with a saga that doesn't have a 1 to 1 correlation of Id or property? I'm looking at doing something like the following but CorrelateBy does not seem to hydrate the saga or trigger off any processing.

    public interface SubmitOrder
    {
        Guid OrderId { get; }

        string[] ItemIds { get; }
    }

    public interface ItemStockExhausted
    {
        string Id { get; }
    }

    public class OrderState :
        SagaStateMachineInstance
    {
        public Guid CorrelationId { get; set; }

        public string[] ItemIds { get; set; }

        public int CurrentState { get; set; }
    }

    public class OrderStateMachine :
        MassTransitStateMachine<OrderState>
    {
        public OrderStateMachine()
        {
            InstanceState(x => x.CurrentState);
            Event(() => SubmitOrder, x
                => x.CorrelateById(context => context.Message.OrderId)
            );

            Event(() => ItemStockExhausted, x
                => x.CorrelateBy((state, context) => state.ItemIds.Contains(context.Message.Id))
            );

            Initially(
                When(SubmitOrder)
                    .Then(x => x.Instance.ItemIds = x.Data.ItemIds)
                    .TransitionTo(Submitted));

            During(Submitted,
                When(ItemStockExhausted)
                    .Then(x => { /* Do something */ })
                    );
        }

        public Event<SubmitOrder> SubmitOrder { get; private set; }

        public Event<ItemStockExhausted> ItemStockExhausted { get; private set; }

        public State Submitted { get; private set; }
    }

Not sure if it makes any difference but I'm using the MongoDB persistence.

1

There are 1 answers

2
Alexey Zimarev On BEST ANSWER

Correlation by the query is possible for Saga persistence providers that support queries. MongoDB persistence provider supports using queries but you need to remember that not LINQ queries translate to MongoDB queries properly.

In your case, I would advise enabling MongoDB query tracing, like it's suggested in this question: How do I log my queries in MongoDB C# Driver 2.0?

Some persistence providers, specifically those that are using key-value databases like Redis, won't support the correlation by queries but they normally throw the "unsupported" exception as soon as you try using a query.