Skip to content

2. Creating a StateEngine

Ovan Crone edited this page Apr 11, 2018 · 6 revisions

So far we have seen REstateHost, Agent, and Schematic<TState, TInput>, but we haven't done anything interesting with those pieces; that is about to change...

The StateEngine<TState, TInput>

StateEngines are state and input type-specific objects that allow you to:

  • Store Schematic<TState, TInput> in a common repository
  • Retrieve stored Schematics
  • Create Machines to run Schematics
  • Retrieve previously-created Machines
  • Delete Machines

Creating a StateEngine

In Creating a Schematic we defined a schematic that used string as its state and input types. We will do the same here, because Schematics, Machines, and Engines all must share the same type parameters.

Here is the Schematic again as a reminder:

var schematic = REstateHost.Agent
    .CreateSchematic<string, string>("LoggerMachine")
    .WithState("Created", state => state
        .AsInitialState())
    .WithState("Ready", state => state
        .WithTransitionFrom("Created", "log")
        .WithReentrance("log")
        .Action("log info", onEntry => onEntry
            .DescribedAs("Logs the payload as a message.")
            .WithSetting(
                key: "messageFormat", 
                value: "{schematicName}({machineId}) entered {state} on {input}. " +
                       "Message: {payload}")))
    .Build();

and to create the StateEngine:

var stateEngine = REstateHost.Agent
    .GetStateEngine<string, string>();

That is pretty much it!

Storing Schematics

Now that we have an engine that is compatible with our Schematic, we can store it in the repository...

var immutableSchematic = await stateEngine.StoreSchematicAsync(schematic);

Storing or retrieving schematics will return the ISchematic<TState, TInput> interface, which is immutable.

To create a copy of an immutable Schematic just call .Clone() to create a mutable Schematic<TState, TInput>. This can be useful for small programmatic changes that may need to be templated from an original Schematic, without replacing or directly modifying it.

var mutableSchematic = immutableSchematic.Clone();

Retrieving Schematics

A Schematic that has been stored can be retrieved by its name, which was defined as schematic.SchematicName on the schematic itself.

var storedSchematic = await stateEngine.GetSchematicAsync("LoggerMachine");

What's next?

We will Create Machines using this StateEngine and Schematic.