Skip to content
Daniel Little edited this page Mar 6, 2016 · 4 revisions

Sagas are an effective way of dealing with temporal problems. The typical job of a Saga is to take in one or more Events and send one or More Commands. They can hold their own state such as storing the Events that they receive but should never access any external state or data.

MicroBus provides basic support for Sagas out of the box, but you'll need to write your own Saga Repository to store them. Each Saga you create gets it's own repository which implements ISagaRepository<YourSagaType>. This interface requires you to define how each saga can be found given a message, how to save it to a data-store and how to remove it when the Saga is complete.

For our example we'll walk through creating a saga for an automated car factory. The Saga will be the Order Shipping Saga and it will listen for two events, the OrderCreatedEvent and the CarBuiltForOrderEvent. Once it's received those two events it'll send out a ShipOrderCommand.

Next we'll go about creating the Saga to start we'll need a class that inherits from ISaga.

public class OrderShippingSaga : ISaga
{
    public bool IsCompleted { get; protected set; }
} 

Saga starting events...

 ISagaStartedBy<OrderCreatedEvent>, 

Saga handling events...

IEventHandler<CarBuiltForOrderEvent>

Note if you're using MicroBus inside a Service Bus the command you send should go out over the Service Bus!

Now that we have our Repository and our Saga it's time to wire them up. First off we'll register the OrderShippingSagaRepository to Autofac.

builder.RegisterType<OrderShippingSagaRepository>().AsImplementedInterfaces().SingleInstance();

Then we just need to register the Saga to the Bus Builder.

var busBuilder = new BusBuilder()
    .RegisterSaga<TestSaga>();

Now when we receive our events, the Saga will process them!

Clone this wiki locally