NStateManager Build status NuGet Status Security Rating Reliability Rating Maintainability Rating

Background and Goals

NStateManager is a .Net library for managing:

This project was created while developing cloud-based solutions. We needed a state management solution made for our stateless services.


Configuring the state machine

//State machine to manage sales for a point of sale system
stateMachine = new StateMachine<Sale, SaleState, SaleEvent>(
  stateAccessor: (sale) => sale.State,                //stateAccessor is used to retrieve the current state
  stateMutator: (sale, state) => sale.State = state); //stateMutator updates state based on transition rule below

//Log each time a sale changes state regardless of to/from state
stateMachine.RegisterOnTransitionedAction((sale, transitionDetails) 
  => Output.WriteLine($"Sale {sale.SaleID} transitioned from {transitionDetails.PreviousState} to {transitionDetails.CurrentState}."));

//Configure the Open state
  //Process the new item on the AddItem event 
  .AddTriggerAction<SaleItem>(SaleEvent.AddItem, (sale, saleItem) => { sale.AddItem(saleItem); })
  //Process the payment on the Pay event
  .AddTriggerAction<Payment>(SaleEvent.Pay, (sale, payment) => { sale.AddPayment(payment); })
  //Transition to the ChangeDue state on Pay event if customer over pays
  .AddTransition(SaleEvent.Pay, SaleState.ChangeDue, condition: sale => sale.Balance < 0, name: "Open2ChangeDue", priority: 1)
  //Transition to the Completed state on Pay event if customer pays exact amount
  .AddTransition(SaleEvent.Pay, SaleState.Complete, condition: sale => sale.Balance == 0, name: "Open2Complete", priority: 2);

//Configure the ChangeDue state
  //Process the returned change on the ChangeGiven event
  .AddTriggerAction<Payment>(SaleEvent.ChangeGiven, (sale, payment) => { sale.ReturnChange(); })
  //Transition to the Complete state on ChangeGiven -- no conditions
  .AddTransition(SaleEvent.ChangeGiven, SaleState.Complete);

//No configuration required for Complete state since it's a final state and
//no state transitions or actions are allowed at this point

Using the state machine

//Add an item to a sale
stateMachine.FireTrigger(sale, SaleEvent.AddItem, saleItem); 

//Add a payment to a sale
stateMachine.FireTrigger(sale, SaleEvent.Pay, payment);

//Give the customer their change
stateMachine.FireTrigger(sale, SaleEvent.ChangeGiven, payment);

For a walkthough of the above code, go to the Quick Start. You can also look at the Wiki for additional details.


Feedback, questions, advice, and contributions are always welcomed so feel free to leave your thoughts in Issues.


Easy to use and very flexible finite state manager for .Net.

Nstatemanager Info

⭐ Stars 19
🔗 Source Code github.com
🕒 Last Update 8 months ago
🕒 Created 5 years ago
🐞 Open Issues 9
➗ Star-Issue Ratio 2
😎 Author scottctr