Skip to content

Instantly share code, notes, and snippets.

@fjeldstad
Last active October 6, 2015 20:22
Show Gist options
  • Save fjeldstad/029510a3ab6dc0ed381e to your computer and use it in GitHub Desktop.
Save fjeldstad/029510a3ab6dc0ed381e to your computer and use it in GitHub Desktop.
public class CustomerRevenueSaga : Saga<CustomerRevenue>
{
public CustomerRevenueSaga(ICustomerRevenueStore store)
{
When<OrderPlaced>(
accessMemory: async msg => new Memory(await store.GetByCustomerId(msg.CustomerId), store.Save),
transform: (msg, state) =>
{
var nextState = state?.Clone() ?? new CustomerRevenue { CustomerId = msg.CustomerId };
nextState.PendingOrderAmounts[msg.Id] = msg.Amount;
return Task.FromResult<ITransformResult>(new TransformResult(nextState));
});
When<OrderCancelled>(
accessMemory: async msg => new Memory(await store.GetByOrderId(msg.OrderId), store.Save),
transform: (msg, state) =>
{
var nextState = state?.Clone();
nextState?.PendingOrderAmounts.Remove(msg.OrderId);
return Task.FromResult<ITransformResult>(new TransformResult(nextState));
});
When<OrderDelivered>(
accessMemory: async msg => new Memory(await store.GetByOrderId(msg.OrderId), store.Save),
transform: (msg, state) =>
{
var nextState = state?.Clone();
var orderAmount = nextState?.PendingOrderAmounts[msg.OrderId];
if (orderAmount.HasValue)
{
nextState.AggregatedRevenue += orderAmount.Value;
nextState.PendingOrderAmounts.Remove(msg.OrderId);
}
return Task.FromResult<ITransformResult>(new TransformResult(nextState));
});
}
}
@fjeldstad
Copy link
Author

To create an instance + connect it to a bus (automatically wiring up topic subscriptions):

var saga = new CustomerRevenueSaga(myStore);
await saga.Connect(myBus);

The base Saga definition, for reference: https://gist.github.com/Hihaj/8c9d002a0e1eb545261b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment