Search code examples
c#nservicebussaganservicebus-sagas

Saga Wait for Status value


I have a Saga which should wait for a specific Database-Value to be changed. How do I achieve this?

Example:

public partial class OrderSaga : Saga<OrderSagaData>, IHandleMessages<FinishOrder> {
   public void Handle(FinishOrder message)
   {
      Order order=new Order(message.OrderId);
      if (order.Approved) {
         SendMail(order);
      }
   }
}

When the bool "Approved" of that Order is true I want to send a mail. But this can take hours or even days. How do I tell the Saga to check again in a few hours? I am new to Sagas and NServiceBus so the answer might be trivial, but I just did not find it.


Solution

  • You can defer any incoming message if you're still waiting for another condition to be met. This will apply a time-out to the message and put it back on the bus for future processing.

    Depending on whether you're using NServiceBus 4 or 5, the method signature for a deferral will change but let's assume you're on V4, you can then do something along the lines of this:

    if (!order.Approved)
    {
        Bus.Defer(TimeSpan.FromHours(1), message);
        //This will defer message handling by an hour
    }
    else
    {
        SendMail(order);
    }