dotnet-state-machine / stateless

A simple library for creating state machines in C# code
Other
5.6k stars 766 forks source link

Question: How to best structure the code (best practices/guidelines) #455

Open k2ibegin opened 3 years ago

k2ibegin commented 3 years ago

Project type: ASP Net Core 5 Web API

Hi, I am planning to use stateless for simple state machine that is expected to grow over time with more states. My idea is to not have the code maintenance nightmare down the road as more conditions/business rules are introduced for a state change.

Currently I have a web app and I have followed samples and threads on Stack overflow to get basic understanding of how to configure statemachiine. However, I am struggling with best guidance/practices.

I am using RDBMS where the state of the object along with other properties is stored. Now the object state(enum) can change by different clients (depending upon validations). I am struggling with following points.

  1. Since we have current state of an entity and changes saved in DB, and we are always interested in the current state of entity in order to perform business logic, I want to have my business logic centralise and encapsulated based on state transitions. I know this library provides a lot of features, but would it be overkill to use it for my use case ?
  2. I plan to use OnEntry methods to perform the business logic prior to saving a new/updated state of object to DB. However, since I want to store the new state in DB in OnEntry, I am unable to get how can I then return the new state to Http Web API controller, as it is indeed not event based mechanism but a request response mechanism, I see no way from OnEntry to be able to return new state to the caller which is awaiting for machine to finish the job.
  3. In order to manage concurrency issues I found the ThreadStateless sample via Rx , however, issue for me is still the same as above.

I am therefore inclined to simply use state machine in following way

  1. API received request (http patch)
  2. Service handles and initialises state machine with current state
  3. I trigger new state based on argument from http patch
  4. trigger succeeds (based on state machine configuration)
  5. I go ahead and update DB with new state. (on trigger fail no update is done in DB)

I see an issue here though, that potentially two threads might be wanting to do contradictory logic and may end up succeeding even though not allowed to do so.

is it okay to use state machine logic the way I mentioned ? I am just looking for right approach for my use case

Thanks a lot for the read :)