Skip to content

Introduction

Immediate.Handlers is a compile-time mediator for .NET, built entirely on source generation.

2 min read
Immediate.Handlers GitHub repository Immediate.Handlers NuGet version Immediate.Handlers latest GitHub release Immediate.Handlers license

Immediate.Handlers is an implementation of the mediator pattern in .NET using source generation. Every pipeline behavior is resolved and the call tree is built at compile time, so the handler you consume is an ordinary class with an ordinary constructor — there is no runtime assembly scanning, no reflection, and no service-locator lookup on the request path. Dependencies still come from Microsoft.Extensions.DependencyInjection at runtime, but which dependencies are needed was decided by the compiler.

Installation

dotnet add package Immediate.Handlers

A minimal example

A handler is a class marked with [Handler] that contains exactly one private Handle or HandleAsync method.

GetUsersQuery.cs
using Immediate.Handlers.Shared;

namespace Application;

[Handler]
public sealed partial class GetUsersQuery(UsersService usersService)
{
	public sealed record Query;

	public sealed record Response(int Id, string Name);

	private async ValueTask<IEnumerable<Response>> HandleAsync(
		Query query,
		CancellationToken token
	)
	{
		var users = await usersService.GetUsers(token);
		return users.Select(u => new Response(u.Id, u.Name));
	}
}

Register the generated handlers and behaviors at startup:

Program.cs
builder.Services.AddApplicationBehaviors();
builder.Services.AddApplicationHandlers();

Then inject the generated GetUsersQuery.Handler wherever you need it:

UsersEndpoint.cs
public sealed class UsersEndpoint(GetUsersQuery.Handler handler)
{
	public async ValueTask<IEnumerable<GetUsersQuery.Response>> GetUsers(CancellationToken token) =>
		await handler.HandleAsync(new GetUsersQuery.Query(), token);
}

The Application in AddApplicationHandlers comes from the assembly name. See The assembly identifier for how that name is derived and how to override it.

Where to next