简体   繁体   中英

Stateless : How to define the initial substate of a state?

I am using stateless to implement logic of a state machine in our application.We have an AcceptedFile state that has other inner (sub)states.The problem is I don't know how should I indicate initial inner state in my code so that when a machine transit to AccptedFile state it would also automatically transit to its initial inner state.Here's what I did to simulate this behavior :

 machine.Configure(State.AcceptedFile)
                    .OnEntry(() => machine.Fire(Trigger.MakeReadyForAdvertising))
                    .Permit(Trigger.MakeReadyForAdvertising,State.ReadyForAdvertising)

here ReadyForAdvertising is an inner state of AcceptedFile .This works fine in most of the scenarios but whenever I set the initial state of my state machine to AcceptedFile like this :

var statemachine=new StateMachine<State,Trigger>(State.AcceptedFile)
...

The automatic transition would not happen thus machine will be in AcceptedFile state instead of ReadyForAdvertising .

Is there a better way to implement this behavior ?

The documentation in StateMachine.cs states:

Substates inherit the allowed transitions of their superstate. When entering directly into a substate from outside of the superstate, entry actions for the superstate are executed. Likewise when leaving from the substate to outside the superstate, exit actions for the superstate will execute.

So if ReadyForAdvertising is your default inner state, just set the initial state to ReadyForAdvertising (or transition to it when the appropriate trigger is received)

var statemachine=new StateMachine<State,Trigger>(State.ReadyForAdvertising)

This will execute the entry actions for AcceptedFile & ReadyForAdvertising and make your current state ReadyForAdvertising.

That seems to be the designed way. OnExit is the safest place to handle it, given its stateless nature.

This is now possible with Stateless. You can configure the initial state of your substates, like so:

machine.Configure(State.AcceptedFile)
    .InitialTransition(State.ReadyForAdvertising);

Link: https://github.com/dotnet-state-machine/stateless#initial-state-transitions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM