-
Notifications
You must be signed in to change notification settings - Fork 7
Event Actions
You can configure your states to execute an action when an event occurs. Executing your actions through NStateManager will help manage the association between behavior and state in your solution.
Here's an example of sending a notification when a sale is cancelled in the Open state.
_stateMachine.ConfigureState(SaleState.Open)
.AddTriggerAction(SaleEvent.SaleCancelled, SendCancelNotification);Many times you'll need parameters to execute your event actions. Here's an example of adding items to a sale that requires a SaleItem to describe the item being added.
_stateMachine.ConfigureState(SaleState.Open)
.AddTriggerAction<SaleItem>(SaleEvent.AddItem, (sale, saleItem) => { sale.AddItem(saleItem); })When your trigger actions include parameters, you'll have to provide the parameter when calling FireTrigger for that event. Here's a sample FireTrigger for the AddItem trigger above.
var saleItem = new SaleItem("Magazine", 2.99);
_stateMachine.FireTrigger(sale, SaleEvent.AddItem, saleItem);What if you want to take the same action for a trigger across all of your states? You can define the trigger action on the state machine instead of a specific state. Here's the notification for cancelling a sale on the state machine.
_stateMachine
.AddTriggerAction(SaleEvent.SaleCancelled, SendCancelNotification);It's important to understand that trigger actions execute before any transition conditions are evaluated. This means that if I'm managing a bank account, the Deposit trigger action will execute before the condition to reach Gold status so the condition can use the balance after the deposit was applied to the account.