How to Register a Microsoft Agent Framework Workflow in ASP.NET Core with AddWorkflow
AddWorkflow registers a Microsoft Agent Framework workflow in an ASP.NET Core app under a name, so any endpoint can ask for it by that name and run it. Here a one-step workflow answers GET /greet/Ana with "Hello, Ana!", from a single workflow that every request shares.
AddWorkflow comes from Microsoft.Agents.AI.Hosting, the package that connects agents and workflows to the .NET host and its dependency injection. It's a preview package. Microsoft's self-hosting guide says the .NET hosting packages are prerelease, and adds: Install prerelease versions explicitly and review release notes before updating a production deployment.
Syntax
builder.AddWorkflow("<name>", (<services>, <workflowName>) =>
{
// <create the executors>
return new WorkflowBuilder(<startExecutor>)
.WithName(<workflowName>)
// <the workflow's edges and outputs>
.Build();
});
app.MapGet("<route>", async ([FromKeyedServices("<name>")] Workflow <workflow>) =>
{
// <run the workflow and return its output>
});
| Part | What it is |
|---|---|
<name> | The name the workflow is registered under. Endpoints ask for the workflow by it |
<services> | The app's IServiceProvider, for anything the workflow needs from dependency injection |
<workflowName> | The same name, handed to your function. Pass it to WithName: AddWorkflow checks that the workflow carries it |
<startExecutor> | The executor that receives each run's input |
[FromKeyedServices("<name>")] | Gets the workflow registered under that name into the endpoint |
<workflow> | The registered workflow, ready to run |
AddWorkflow also takes an optional fourth argument, the workflow's ServiceLifetime, which is Singleton unless you pass another. Its documentation describes the function: A factory function that creates the Workflow instance. The function receives the service provider and workflow name as parameters.
The Example
An ASP.NET Core API called GreetingApi registers a workflow named greeting with one step, GreetPerson, a function that turns a name into a greeting. An endpoint, GET /greet/{person}, gets the workflow, runs it with the person's name and returns the greeting. Nothing in it calls a model, so running it costs nothing.
Prerequisites
- The .NET 10 SDK.
- A way to send
.httpfiles: Visual Studio, or VS Code with the REST Client extension.
Step 1: Create an Empty ASP.NET Core App and Add the Packages
dotnet new web -o GreetingApi
cd GreetingApi
The template "ASP.NET Core Empty" was created successfully.
Processing post-creation actions...
Restoring /Users/you/source/GreetingApi/GreetingApi.csproj:
Restore succeeded.
dotnet new web creates an empty ASP.NET Core app in a new folder, GreetingApi, and cd moves into it. Then add two packages:
dotnet add package Microsoft.Agents.AI.Workflows --version 1.28.0
dotnet add package Microsoft.Agents.AI.Hosting --version 1.28.0-preview.261106.1
Each command adds a package reference and restores the project. The second one ends like this:
info : PackageReference for package 'Microsoft.Agents.AI.Hosting' version '1.28.0-preview.261106.1' added to file '/Users/you/source/GreetingApi/GreetingApi.csproj'.
info : Writing assets file to disk. Path: /Users/you/source/GreetingApi/obj/project.assets.json
log : Restored /Users/you/source/GreetingApi/GreetingApi.csproj (in 694 ms).
Microsoft.Agents.AI.Workflowsis Agent Framework's workflow library: executors, edges andWorkflowBuilder.Microsoft.Agents.AI.HostingaddsAddWorkflow. It's the preview package, as its version says.
The project file now lists both:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Agents.AI.Hosting" Version="1.28.0-preview.261106.1" />
<PackageReference Include="Microsoft.Agents.AI.Workflows" Version="1.28.0" />
</ItemGroup>
</Project>
Step 2: Register the Workflow with AddWorkflow
Replace everything in Program.cs with this:
using Microsoft.Agents.AI.Hosting;
using Microsoft.Agents.AI.Workflows;
var builder = WebApplication.CreateBuilder(args);
// Register the workflow under its name. The function builds it once, the first time it's needed.
builder.AddWorkflow("greeting", (services, name) =>
{
Func<string, string> greet = person => $"Hello, {person}!";
// threadsafe: the function keeps nothing between messages, so several requests can share it.
ExecutorBinding greetPerson = greet.BindAsExecutor("GreetPerson", threadsafe: true);
return new WorkflowBuilder(greetPerson)
.WithName(name)
.WithOutputFrom(greetPerson)
.Build();
});
AddWorkflow("greeting", ...)registers the workflow under the namegreeting. It doesn't build it yet: the lifetime isSingleton, and a singleton is created the first time something asks for it. Every request after that gets the same workflow.(services, name)are the app's service provider and the registered name,greeting.BindAsExecutor("GreetPerson", threadsafe: true)turns the greeting function into the workflow's one executor.threadsafe: trueis a promise: its documentation says it declares that the message handler may be used simultaneously by multiple runs concurrently. The promise holds here, because the function keeps nothing between messages..WithName(name)gives the workflow the registered name.AddWorkflowchecks it when it first creates the workflow, and a missing or different name fails that request with 500: Fixed: The workflow factory returned workflow with name '', but the expected name is 'greeting'..WithOutputFrom(greetPerson)makes the greeting the workflow's output.
Step 3: Run the Workflow from an Endpoint
Add the endpoint and start the app, below the registration:
var app = builder.Build();
app.MapGet("/greet/{person}", async (string person, [FromKeyedServices("greeting")] Workflow workflow) =>
{
await using Run run = await InProcessExecution.Concurrent.RunAsync(workflow, person);
string? greeting = run.OutgoingEvents.OfType<WorkflowOutputEvent>().Select(output => output.Data as string).FirstOrDefault();
return greeting is null ? Results.Problem("The workflow returned nothing.") : Results.Ok(greeting);
});
app.Run();
string personcomes from the route, the{person}part of/greet/{person}.[FromKeyedServices("greeting")] Workflow workflowgets the workflow registered asgreeting.AddWorkflowregisters it as a keyed service with its name as the key, and How to Inject a Keyed Service with [FromKeyedServices] in .NET C# covers the attribute itself.InProcessExecution.Concurrent.RunAsync(workflow, person)runs the workflow for this request. All requests share one workflow, and the concurrent mode is the one that allows multiple runs to share the same workflow instance simultaneously, in the words of Microsoft's execution modes page. It needs every executor to be safe to share between runs, and for a function executor that's whatthreadsafe: truedeclares.run.OutgoingEventsholds the run's events. TheWorkflowOutputEventcarries the greeting, andResults.Ok(greeting)returns it with status 200. If no output arrives,Results.Problemanswers with a problem response instead.app.Run()starts the API.
How to Run One Microsoft Agent Framework Workflow for Many Requests at Once in C# shows the concurrent mode in detail, with the other way to make it work: an executor created for each run.
Step 4: Start the API
dotnet run
Using launch settings from /Users/you/source/GreetingApi/Properties/launchSettings.json...
Building...
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5010
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/you/source/GreetingApi

The API is listening on http://localhost:5010, the address in Properties/launchSettings.json. The template chose that port when it created the project: for new ASP.NET Core projects, the configuration selects a random HTTP port between 5000-5300, so your port is likely a different one. Use yours in the next step.
Step 5: Send a Request
Save this request as GreetingApi.http in the project folder, with your port in baseUrl:
@baseUrl = http://localhost:5010
GET {{baseUrl}}/greet/Ana
###
@baseUrl is a variable, and {{baseUrl}} puts it into the request. The request asks the endpoint to greet Ana. Send it from your editor; How to Send API Requests from a .http File in VS Code and Visual Studio shows how in both.
HTTP/1.1 200 - OK
content-type: application/json; charset=utf-8
server: Kestrel
transfer-encoding: chunked
"Hello, Ana!"
The workflow ran for the request, and its output came back as JSON: the string "Hello, Ana!". To stop the API, press Ctrl+C in its terminal.
The Complete File
using Microsoft.Agents.AI.Hosting;
using Microsoft.Agents.AI.Workflows;
var builder = WebApplication.CreateBuilder(args);
// Register the workflow under its name. The function builds it once, the first time it's needed.
builder.AddWorkflow("greeting", (services, name) =>
{
Func<string, string> greet = person => $"Hello, {person}!";
// threadsafe: the function keeps nothing between messages, so several requests can share it.
ExecutorBinding greetPerson = greet.BindAsExecutor("GreetPerson", threadsafe: true);
return new WorkflowBuilder(greetPerson)
.WithName(name)
.WithOutputFrom(greetPerson)
.Build();
});
var app = builder.Build();
app.MapGet("/greet/{person}", async (string person, [FromKeyedServices("greeting")] Workflow workflow) =>
{
await using Run run = await InProcessExecution.Concurrent.RunAsync(workflow, person);
string? greeting = run.OutgoingEvents.OfType<WorkflowOutputEvent>().Select(output => output.Data as string).FirstOrDefault();
return greeting is null ? Results.Problem("The workflow returned nothing.") : Results.Ok(greeting);
});
app.Run();

Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Leaving out .WithName(name) | The first request that needs the workflow fails with 500: the workflow factory returned workflow with name '' | Name the workflow with the name parameter |
Running the shared workflow with InProcessExecution.RunAsync | A run takes ownership of the workflow, so a second request during a run can't use it | Use InProcessExecution.Concurrent |
Declaring threadsafe: true for a function that keeps data between messages | Every request shares that data | Keep shared executors stateless, or give each request its own workflow |
FAQ
Why is one workflow shared by every request?
Because AddWorkflow registers it as a singleton unless you pass another lifetime, and for a singleton, Every subsequent request of the service implementation from the dependency injection container uses the same instance. The same documentation adds Singleton services must be thread safe and are often used in stateless services. That's the reason for threadsafe: true, a function that keeps nothing, and the concurrent execution mode.
Can each request get a workflow of its own?
Yes, through the lifetime argument. A transient service is created each time it's requested, so with ServiceLifetime.Transient your function builds a new workflow whenever an endpoint asks for one. Microsoft's guidance on workflow state prefers that for isolation: it is recommended to create a new workflow instance from the builder for each task or request to ensure proper state isolation and thread safety. The price is building the workflow on every request.
Conclusion
To register a Microsoft Agent Framework workflow in ASP.NET Core, call builder.AddWorkflow("<name>", ...) with a function that builds the workflow and names it with .WithName(name), then take it into an endpoint with [FromKeyedServices("<name>")]. GreetingApi's workflow is built at the first request and shared by every request after it, so its one executor is declared threadsafe and each run uses InProcessExecution.Concurrent. GET /greet/Ana returned 200 and "Hello, Ana!".
Additional Resources
- Self-host Agent Framework applications —
AddWorkflow,AddAIAgentand the hosting package. - Workflow Execution Modes —
InProcessExecution.Concurrentand what it requires. - Service lifetimes — singleton, scoped and transient services.
- Configure endpoints for the ASP.NET Core Kestrel web server — the ports in
launchSettings.json.
