Skip to main content

How to Write a Class-Based Workflow Executor in Microsoft Agent Framework in C#

· 11 min read
Jagdish Kumawat
Founder @ Dewiride

A class-based executor is a Microsoft Agent Framework workflow step written as a C# class: a partial class that derives from Executor, with one method marked [MessageHandler] that takes the step's input and returns its result. This guide writes two of them, one that cleans a text and one that counts its words, and connects them into a workflow.

Syntax​

Syntax
internal sealed partial class <ClassName>() : Executor("<executorId>")
{
[MessageHandler]
private <TOutput> Handle(<TInput> message, IWorkflowContext context) => <result>;
}
PartWhat it is
partialLets the workflows source generator add the rest of the class while the project builds. Microsoft's Executors guide: The class must be marked partial to enable source generation.
<ClassName>Your class's name.
Executor("<executorId>")The base class. Its constructor takes the executor's id, documented as A unique identifier for the executor. Events name the executor by this id.
[MessageHandler]Marks the method that receives the executor's messages. Its documentation: The method signature determines the input type and optional output type.
<TInput> messageThe type of message the executor accepts, and the message itself.
<TOutput> and <result>What the method returns. Microsoft's sample notes: Return value is automatically sent to connected executors.
IWorkflowContext contextThe run's services for this executor, documented as Provides services for an Executor during the execution of a workflow. Sending more messages and yielding an output go through it.

The documentation of MessageHandlerAttribute in Agent Framework 1.28.0 lists every shape the method can have: with or without a result, synchronous or asynchronous, and with or without a CancellationToken:

Handler signatures
void Handler(TMessage, IWorkflowContext)
void Handler(TMessage, IWorkflowContext, CancellationToken)
ValueTask Handler(TMessage, IWorkflowContext)
ValueTask Handler(TMessage, IWorkflowContext, CancellationToken)
TResult Handler(TMessage, IWorkflowContext)
TResult Handler(TMessage, IWorkflowContext, CancellationToken)
ValueTask<TResult> Handler(TMessage, IWorkflowContext)
ValueTask<TResult> Handler(TMessage, IWorkflowContext, CancellationToken)

The ValueTask forms are for a handler that awaits something, such as an agent. The forms without a result don't send anything on by returning; such a handler uses context to send messages or produce output.

The Example​

A console app called WordCount has two executors. CleanText takes a text and returns it without its extra spaces. CountWords takes that clean text and returns how many words it has. The workflow runs them in that order on the words the quick brown fox, written with extra spaces before, between and after them, and its output is 4. There's no AI model in it, so you don't need an Azure account.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

In a terminal, in the folder where you keep your projects, create the app and move into it:

Terminal
dotnet new console -o WordCount
cd WordCount
Output (first command)
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/WordCount/WordCount.csproj:
Restore succeeded.

dotnet new console creates a console app in a new WordCount folder, and cd moves into it. Open the folder in VS Code, or WordCount.csproj in Visual Studio.

Step 2: Add the Two Workflows Packages​

Add Agent Framework's workflows package:

Terminal
dotnet add package Microsoft.Agents.AI.Workflows --version 1.28.0
Output
info : X.509 certificate chain validation will use the fallback certificate bundle at '/usr/local/share/dotnet/sdk/10.0.404/trustedroots/codesignctl.pem'.
info : X.509 certificate chain validation will use the fallback certificate bundle at '/usr/local/share/dotnet/sdk/10.0.404/trustedroots/timestampctl.pem'.
info : Adding PackageReference for package 'Microsoft.Agents.AI.Workflows' into project '/Users/you/source/WordCount/WordCount.csproj'.
info : Restoring packages for /Users/you/source/WordCount/WordCount.csproj...
info : CACHE https://api.nuget.org/v3/vulnerabilities/index.json
info : CACHE https://api.nuget.org/v3-vulnerabilities/2026.11.20.05.34.20/vulnerability.base.json
info : CACHE https://api.nuget.org/v3-vulnerabilities/2026.11.20.05.34.20/2026.11.30.11.35.26/vulnerability.update.json
info : Package 'Microsoft.Agents.AI.Workflows' is compatible with all the specified frameworks in project '/Users/you/source/WordCount/WordCount.csproj'.
info : PackageReference for package 'Microsoft.Agents.AI.Workflows' version '1.28.0' added to file '/Users/you/source/WordCount/WordCount.csproj'.
info : Generating MSBuild file /Users/you/source/WordCount/obj/WordCount.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/you/source/WordCount/obj/project.assets.json
log : Restored /Users/you/source/WordCount/WordCount.csproj (in 1.16 sec).

Microsoft.Agents.AI.Workflows has everything a workflow is made of: executors, edges, the builder and the code that runs a workflow. --version keeps you on the version this guide used.

Then add its source generator:

Terminal
dotnet add package Microsoft.Agents.AI.Workflows.Generators --version 1.28.0

A source generator is a tool that runs while the project compiles and adds code to it. This one writes the code that registers each [MessageHandler] method with the workflow. Microsoft's note on the package: Source generator packages don't flow transitively, so reference it directly in the project that defines the executors. Without it, every class-based executor fails to build with CS0534 (Fixed).

The project file now has both packages:

WordCount.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Agents.AI.Workflows" Version="1.28.0" />
<PackageReference Include="Microsoft.Agents.AI.Workflows.Generators" Version="1.28.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

</Project>

The generator's reference got IncludeAssets and PrivateAssets because the package marks itself as a development dependency: it runs when this project builds and isn't passed on to projects that reference this one.

Step 3: Write the First Executor​

Replace everything in Program.cs with the first executor. The code that runs the workflow goes above it in Step 5: in a file like this one, C#'s classes must come after the top-level statements, the code at the root of the file.

Program.cs
using Microsoft.Agents.AI.Workflows;

// Step 1: takes a text and returns it without its extra spaces.
internal sealed partial class CleanTextExecutor() : Executor("CleanText")
{
[MessageHandler]
private string Handle(string text, IWorkflowContext context) =>
string.Join(' ', text.Split(' ', StringSplitOptions.RemoveEmptyEntries));
}
  • internal sealed partial class CleanTextExecutor() declares the class. partial lets the generator add its part. The empty () after the name gives the class a constructor without parameters.
  • : Executor("CleanText") derives the class from Executor and passes the executor's id, CleanText, to its constructor.
  • [MessageHandler] marks Handle as the method that receives this executor's messages. Its first parameter is a string, so it accepts text, and it returns a string.
  • The method's body splits the text at every space. The extra spaces leave empty pieces, which StringSplitOptions.RemoveEmptyEntries drops, and string.Join puts the words back together with one space between them.

Step 4: Write the Second Executor​

Add the second executor at the end of the file:

Program.cs (add at the end)
// Step 2: takes a clean text and returns how many words it has.
internal sealed partial class CountWordsExecutor() : Executor("CountWords")
{
[MessageHandler]
private int Handle(string text, IWorkflowContext context) => text.Split(' ').Length;
}

CountWords accepts a string, the clean text that CleanText returns, and returns an int. In a clean text the words are separated by exactly one space, so the number of pieces Split(' ') makes is the number of words.

Step 5: Connect the Executors and Run the Workflow​

Add this below the using line, above the two classes:

Program.cs (below the using line)
CleanTextExecutor cleanText = new();
CountWordsExecutor countWords = new();

Workflow workflow = new WorkflowBuilder(cleanText)
.AddEdge(cleanText, countWords)
.WithOutputFrom(countWords)
.Build();

await using Run run = await InProcessExecution.RunAsync(workflow, " the quick brown fox ");

foreach (WorkflowEvent workflowEvent in run.OutgoingEvents)
{
switch (workflowEvent)
{
case ExecutorCompletedEvent completed:
Console.WriteLine($"{completed.ExecutorId} returned: {completed.Data}");
break;
case WorkflowOutputEvent output:
Console.WriteLine($"The workflow's output: {output.Data}");
break;
}
}
  • new() creates one object of each executor class.
  • new WorkflowBuilder(cleanText) starts a workflow whose first step is CleanText, so CleanText receives the input.
  • AddEdge(cleanText, countWords) connects the two steps: what CleanText returns goes to CountWords.
  • WithOutputFrom(countWords) makes CountWords a source of the workflow's output. Its documentation adds: By default, message handlers with a non-void return type will also be yielded. So the number CountWords returns becomes the output, without any more code.
  • InProcessExecution.RunAsync runs the workflow inside the app with the text as its input. Its documentation: The workflow will run until its first halt, and the returned Run will capture all outgoing events. await using disposes of the run when the app is done with it.
  • run.OutgoingEvents is every event the run produced. The loop prints two kinds: ExecutorCompletedEvent, raised when an executor's handler finishes, with the executor's id in ExecutorId and its result in Data, and WorkflowOutputEvent, which carries the workflow's output.

Step 6: Run It​

Terminal
dotnet run
Output
CleanText returned: the quick brown fox
CountWords returned: 4
The workflow's output: 4

macOS-style terminal window titled Terminal — WordCount showing dotnet run printing CleanText returned: the quick brown fox, CountWords returned: 4, and The workflow's output: 4

CleanText returned the words with one space between them, and CountWords counted 4 of them. Because CountWords is the workflow's output, its 4 is also the output. The ids, CleanText and CountWords, are what the events report, not the class names.

The Complete File​

Program.cs
using Microsoft.Agents.AI.Workflows;

CleanTextExecutor cleanText = new();
CountWordsExecutor countWords = new();

Workflow workflow = new WorkflowBuilder(cleanText)
.AddEdge(cleanText, countWords)
.WithOutputFrom(countWords)
.Build();

await using Run run = await InProcessExecution.RunAsync(workflow, " the quick brown fox ");

foreach (WorkflowEvent workflowEvent in run.OutgoingEvents)
{
switch (workflowEvent)
{
case ExecutorCompletedEvent completed:
Console.WriteLine($"{completed.ExecutorId} returned: {completed.Data}");
break;
case WorkflowOutputEvent output:
Console.WriteLine($"The workflow's output: {output.Data}");
break;
}
}

// Step 1: takes a text and returns it without its extra spaces.
internal sealed partial class CleanTextExecutor() : Executor("CleanText")
{
[MessageHandler]
private string Handle(string text, IWorkflowContext context) =>
string.Join(' ', text.Split(' ', StringSplitOptions.RemoveEmptyEntries));
}

// Step 2: takes a clean text and returns how many words it has.
internal sealed partial class CountWordsExecutor() : Executor("CountWords")
{
[MessageHandler]
private int Handle(string text, IWorkflowContext context) => text.Split(' ').Length;
}

macOS-style code window titled Program.cs — WordCount showing the two executors created and connected by a WorkflowBuilder with an edge from cleanText to countWords and output from countWords, InProcessExecution.RunAsync with a text full of extra spaces, a loop that prints each completed executor and the workflow's output, and the two partial classes CleanTextExecutor and CountWordsExecutor, each with one MessageHandler method

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out Microsoft.Agents.AI.Workflows.GeneratorsEvery executor class fails with CS0534: it doesn't implement Executor.ConfigureProtocol(ProtocolBuilder) (Fixed)Add the package to the project that defines the executors
Declaring the class without partialMAFGENWF003, plus CS0534 for that class (Fixed)Declare it internal sealed partial class

FAQ​

When should I write a class instead of a function?​

A function bound with BindAsExecutor is enough for a step that turns one input into one output. A class is the place for a step that needs something passed to its constructor, such as an agent, or one that accepts more than one type of message: Microsoft's Executors guide shows a class with two [MessageHandler] methods, one for each input type.

Can a handler send more than its return value?​

Yes, through context. Microsoft's Executors guide shows context.SendMessageAsync, which sends a message to the connected executors, and context.YieldOutputAsync, which produces a workflow output. A handler that sends everything that way can return ValueTask instead of a result.

Conclusion​

A class-based executor is a partial class that derives from Executor, passes its id to the base constructor, and marks one method [MessageHandler]. The method's parameter is what the step accepts, and its return value is what it sends on. Add Microsoft.Agents.AI.Workflows.Generators next to the workflows package so the generator can register the handler, connect the executors with AddEdge, and choose the output with WithOutputFrom.

Additional Resources​

  • Executors — class-based and function-based executors, handlers and IWorkflowContext.
  • Edges — connecting executors, and the install step with both packages.