Fluent .Net State Machine

I was listening to an episode of DNR featuring Chris Patterson who is behind MassTransit, an open source .net service bus.  I’d recently been working a little with NServiceBus so I was interested to hear his take on the subject.  One of the interesting things to come out of the interview was a quick mention of another of his projects, Automatonymous, which is a .net state machine that operates in a fluent interface.

So for example:

public class BigComplexStateMachine :
StateMachine<BigState>
{
//declare states
public State InProcess { get; set; }
public State Delayed { get; set; }
public State OnHold { get; set; }
public State Delivered { get; set; }
//you get 'complete' and 'initial' for free


//declare events
public Event Ordered { get; set; }
public Event Delay { get; set; }
public Event Hold { get; set; }
public Event<CustomEventData> Deliver { get; set; }



//must NOT have arguments
public BigComplexStateMachine()
{
//inform the statemachine of your states
State(() => InProcess);
State(() => Delayed);
State(() => OnHold);
State(() => Delivered);

//inform the statemachine of your events
Event(() => Ordered);
Event(() => Delay);
Event(() => Hold);
Event(() => Deliver);


//define transitions
Initially(
When(Ordered)
.Then(state=> { /*do cool stuff */ })
.TransitionTo(InProcess)
);

During(InProcess,
When(Deliver) //notice the new param available
.Then((state, @event) => { /* do cool stuff */ })
.TransitionTo(OnHold)
);

//so on and so forth
/*
* During(state, When(event).[StuffIWantToDo].TransitionTo(state));
*/
Anytime(When(Hold) //also support an anytime concept
.Then(state=> { /*cool stuff*/ })
.Complete() //convenience method

);
}
}

Some more info here as well.
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s