Loading workflows from JSON is a great way to store workflows in a database or file system. This guide will show you how to load workflows from JSON files.
Console application
The most straightforward way to load workflows from JSON files is to simply load the contents of a JSON file, deserialise it and then execute the deserialised workflow.
1
Create Console Project
dotnet new console -n "ElsaConsole" -f net8.0
cd ElsaConsole
dotnet add package Elsa
dotnet add package Elsa.Testing.Shared
2
Update Program.cs
Here's a complete Program.cs file that demonstrates how to load a workflow from a JSON file and execute it:
Program.cs
using Elsa.Extensions;
using Elsa.Testing.Shared;
using Elsa.Workflows.Contracts;
using Elsa.Workflows.Management.Mappers;
using Elsa.Workflows.Management.Models;
using Microsoft.Extensions.DependencyInjection;
// Setup service container.
var services = new ServiceCollection();
// Add Elsa services.
services.AddElsa();
// Build service container.
var serviceProvider = services.BuildServiceProvider();
// Populate registries. This is only necessary for applications that are not using hosted services.
await serviceProvider.PopulateRegistriesAsync();
// Import a workflow from a JSON file.
var workflowJson = await File.ReadAllTextAsync("HelloWorld.json");
// Get a serializer to deserialize the workflow.
var serializer = serviceProvider.GetRequiredService<IActivitySerializer>();
// Deserialize the workflow model.
var workflowDefinitionModel = serializer.Deserialize<WorkflowDefinitionModel>(workflowJson);
// Map the model to a Workflow object.
var workflowDefinitionMapper = serviceProvider.GetRequiredService<WorkflowDefinitionMapper>();
var workflow = workflowDefinitionMapper.Map(workflowDefinitionModel);
// Get a workflow runner to run the workflow.
var workflowRunner = serviceProvider.GetRequiredService<IWorkflowRunner>();
// Run the workflow.
await workflowRunner.RunAsync(workflow);
3
Create Workflow JSON file
Create a new file called HelloWorld.json in the root of the project and make sure it is configured to be copied to the output directory.
In this guide, we've demonstrated configuring an Elsa Server to host workflows from JSON files. We covered loading a JSON file, deserialising it into the Workflow class, and executing the workflow.