Elsa Console
Elsa Workflows can be seamlessly integrated into console applications, offering a lightweight approach to run workflows. This guide will walk you through setting up Elsa in a console application and running a simple workflow.
Setup
First, let's scaffold a new project by following these steps:
Create Console Application
Start by creating a new console application:
dotnet new console -n "ElsaConsole" -f net8.0Add Packages
Navigate to your newly created project's root directory and add the following packages:
cd ElsaConsole dotnet add package ElsaModify Program.cs
Open
Program.cs
and replace its contents with the following:using Elsa.Extensions; using Microsoft.Extensions.DependencyInjection; // Setup service container. var services = new ServiceCollection(); // Add Elsa services to the container. services.AddElsa(); // Build the service container. var serviceProvider = services.BuildServiceProvider();This code sets up a service container and adds Elsa services to it. The
serviceProvider
can be used to resolve Elsa services and run workflows.
Demo 1
Let's start with the most basic thing we can do with Elsa, which is executing an activity.
Add the following code to Program.cs:
using Microsoft.Extensions.DependencyInjection; // Instantiate an activity to run. var activity = new WriteLine("Hello World!"); // Resolve a workflow runner to execute the activity. var workflowRunner = serviceProvider.GetRequiredService<IWorkflowRunner>(); // Execute the activity. await workflowRunner.RunAsync(activity);Run the program using the following command:
dotnet runThe console output should look like this:
Hello World!
Demo 2
Let's try a slightly more interesting workflow, using the Sequence
activity.
Replace the previously added code to Program.cs with the following code:
// Instantiate an activity to run. var activity = new Sequence { Activities = { new WriteLine("Hello World!"), new WriteLine("We can do more than a one-liner!") } }; // Resolve a workflow runner to execute the activity. var workflowRunner = serviceProvider.GetRequiredService<IWorkflowRunner>(); // Execute the activity. await workflowRunner.RunAsync(activity);Run the program using the following command:
dotnet runThe console output should look like this:
Hello World! We can do more than a one-liner!
Summary
In this guide, we created a simple Console application and leveraged Elsa's IWorkflowRunner
service to execute an activity. Activities in Elsa are composable of other activities, which gives rise to the ability to construct complex workflow graphs.
The complete code is available here.