Search code examples
masstransitautomatonymous

Combine to Whens in Automatonymous state machine


I am making a Request from MassTransit state machine saga and wait for reply.

But there could be two errors coming back to me:

  • MyRequest.TimeoutExpired
  • MyRequest.Faulted

I don't care on which conditions the request was not fulfilled, I want both situations to result in an error message to be published.

However, I could not find any way to combine two outcomes with or condition, so I can have one handling case for both outcomes and not copy-paste my code.


Solution

  • In this case, you should either create a custom activity (advanced, probably not necessary) or just create a method that is called from both When() conditions, so that you can reuse the behavior between statements.

    Task PublishEvent(BehaviorContext<TInstance> context)
    {
        var consumeContext = context.GetPayload<ConsumeContext>();
    
        return consumeContext.Publish(new MyEvent(...));
    }
    
    {
        During(MyRequest.Pending,
            When(MyRequest.Completed)
                .ThenAsync(PublishEvent),
            When(MyRequest.Faulted)
                .ThenAsync(PublishEvent));
    }