Immediate.Handlers
3.6.0
dotnet add package Immediate.Handlers --version 3.6.0
NuGet\Install-Package Immediate.Handlers -Version 3.6.0
<PackageReference Include="Immediate.Handlers" Version="3.6.0" />
<PackageVersion Include="Immediate.Handlers" Version="3.6.0" />
<PackageReference Include="Immediate.Handlers" />
paket add Immediate.Handlers --version 3.6.0
#r "nuget: Immediate.Handlers, 3.6.0"
#:package Immediate.Handlers@3.6.0
#addin nuget:?package=Immediate.Handlers&version=3.6.0
#tool nuget:?package=Immediate.Handlers&version=3.6.0
Immediate.Handlers
Immediate.Handlers is an implementation of the mediator pattern in .NET using source-generation. All pipeline behaviors are determined and the call-tree built at compile-time; meaning that all dependencies are enforced via compile-time safety checks. Behaviors and dependencies are obtained via DI at runtime based on compile-time determined dependencies.
Examples
- Minimal Api: Normal
Installing Immediate.Handlers
You can install Immediate.Handlers with NuGet:
Install-Package Immediate.Handlers
Or via the .NET Core command line interface:
dotnet add package Immediate.Handlers
Either commands, from Package Manager Console or .NET Core CLI, will download and install Immediate.Handlers.
Using Immediate.Handlers
Creating Handlers
Create a Handler by adding the following code:
[Handler]
public sealed partial class GetUsersQuery(
UsersService usersService
)
{
public record Query;
private ValueTask<IEnumerable<User>> HandleAsync(
Query _,
CancellationToken token
)
{
return usersService.GetUsers();
}
}
This will automatically create a new class, GetUsersQuery.Handler, which encapsulates the following:
- attaching any behaviors defined for all queries in the assembly
- using a class to receive any DI services, such as
UsersService
Any consumer can now do the following:
public class Consumer(GetUsersQuery.Handler handler)
{
public async Task Consumer(CancellationToken token)
{
var response = await handler.HandleAsync(new(), token);
// do something with response
}
}
For Command handlers, use a ValueTask, and Immediate.Handlers will insert a return type
of ValueTuple to your handler automatically.
[Handler]
public sealed partial class CreateUserCommand()
UsersService usersService
)
{
public record Command(string Email);
private async ValueTask HandleAsync(
Command command,
CancellationToken token
)
{
await usersService.CreateUser(command.Email);
}
}
In case your project layout does not allow direct for references between consumer and handler, the handler will also be
registered as an IHandler<TRequest, Response>.
public class Consumer(IHandler<Query, IEnumerable<User>> handler)
{
public async Task Consumer(CancellationToken token)
{
var response = await handler.HandleAsync(new(), token);
// do something with response
}
}
Creating Behaviors
Create a behavior by implementing the Immediate.Handlers.Shared.Behaviors<,> class, as so:
public sealed class LoggingBehavior<TRequest, TResponse>(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
: Behavior<TRequest, TResponse>
{
public override async ValueTask<TResponse> HandleAsync(TRequest request, CancellationToken cancellationToken)
{
logger.LogInformation("LoggingBehavior.Enter");
var response = await Next(request, cancellationToken);
logger.LogInformation("LoggingBehavior.Exit");
return response;
}
}
Using Behaviors
Once added to the pipeline, the behavior will be called as part of the pipeline to handle a request. They can be added to the pipeline one of three ways:
- Behaviors can be registered assembly-wide by using an
[assembly: ]attribute, as shown here:
[assembly: Behaviors(
typeof(LoggingBehavior<,>)
)]
- Behaviors can be applied on an individual handler using:
[Handler]
[Behavior(
typeof(LoggingBehavior<,>)
)]
public static class GetUsersQuery
{
// ..
}
- Common behavior pipelines can be defined by applying a
[Behaviors]attribute another attribute, as shown here:
[Behaviors(
typeof(ValidationBehavior<,>), typeof(TransactionBehavior<,>)
)]
public sealed class DefaultBehaviorsAttribute : Attribute;
// usage
[Handler]
[DefaultBehaviors]
public sealed class GetUsersQuery
{
// ..
}
Note: adding a [Behavior] attribute to a handler will disregard all assembly-wide behaviors for that handler, so any
global behaviors necessary must be independently added to the handler override behaviors list.
Behavior Constraints
A constraint can be added to a behavior by using:
public sealed class LoggingBehavior<TRequest, TResponse>
: Behavior<TRequest, TResponse>
where TRequest : IRequestConstraint
where TResponse : IResponseConstraint
When a pipeline is generated, all potential behaviors are evaluated against the request and response types, and if either type does not match a given constraint, the behavior is not added to the generated pipeline.
Registering with IServiceCollection
Immediate.Handlers supports Microsoft.Extensions.DependencyInjection.Abstractions directly.
Registering Handlers
In your Program.cs, add a call to services.AddXxxHandlers(), where Xxx is the shortened form of the project name.
- For a project named
Web, it will beservices.AddWebHandlers() - For a project named
Application.Web, it will beservices.AddApplicationWebHandlers()
This registers all classes in the assembly marked with [Handler].
Registering Behaviors
In your Program.cs, add a call to services.AddXxxBehaviors(), where Xxx is the shortened form of the project name.
- For a project named
Web, it will beservices.AddWebBehaviors() - For a project named
Application.Web, it will beservices.AddApplicationWebBehaviors()
This registers all behaviors referenced in any [Behaviors] attribute.
Streaming Handlers
Immediate.Handlers supports streaming handlers that return IAsyncEnumerable<TResponse> for scenarios where
responses are produced incrementally.
Streaming Handler
Create a streaming handler by returning IAsyncEnumerable<TResponse> from the HandleAsync method:
[Handler]
public static partial class StreamItems
{
public record Query(int Count);
private static async IAsyncEnumerable<int> HandleAsync(
Query query,
[EnumeratorCancellation] CancellationToken token)
{
for (var i = 0; i < query.Count; i++)
{
await Task.Yield();
yield return i;
}
}
}
The generated StreamItems.Handler implements IStreamingHandler<StreamItems.Query, int>, allowing consumers to
use either the concrete handler or the interface abstraction:
public class Consumer(IStreamingHandler<StreamItems.Query, int> handler)
{
public async Task ConsumeAsync(CancellationToken token)
{
await foreach (var item in handler.HandleAsync(new(5), token))
Console.WriteLine(item);
}
}
Streaming Behavior
Create a streaming pipeline behavior by extending StreamingBehavior<TRequest, TResponse>:
public class LoggingBehavior<TRequest, TResponse>(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
: StreamingBehavior<TRequest, TResponse>
{
public override async IAsyncEnumerable<TResponse> HandleAsync(
TRequest request,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
logger.LogInformation("LoggingBehavior.Enter");
await foreach (var item in Next(request, cancellationToken))
yield return item;
logger.LogInformation("LoggingBehavior.Exit");
}
}
Using Streaming Behaviors
Streaming behaviors are registered and applied in the same ways as regular behaviors — assembly-wide, per-handler, or via a custom attribute — but they are only applied to streaming handlers. Likewise, non-streaming behaviors are only applied to non-streaming handlers, so both kinds can coexist in the same pipeline configuration without interfering with each other.
Using with Swashbuckle
For Swagger to work the JSON schema generated is required to have unique schemaId's. To achieve this, Swashbuckle uses class names as simple schemaId's. When using Immediate Handlers classes with a controller action inside, you might end up with Swashbuckle stating an error similar to this:
Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorException: Failed to generate schema for type - MyApp.Api.DeleteUser+Command. See inner exception
System.InvalidOperationException: Can't use schemaId "$Command" for type "$MyApp.Api.DeleteUser+Command". The same schemaId is already used for type "$MyApp.Api.CreateUserCommand+Command"
This error indicates Swashbuckle is trying to use two classes named Command from two (or more) different Handlers in different namespaces.
To fix this, you have to define the following options in your SwaggerGen configuration:
builder.Services.AddSwaggerGen( options =>
{
options.CustomSchemaIds(x => x.FullName?.Replace("+", ".", StringComparison.Ordinal));
});
Performance Comparisons
For performance comparisons, check out https://github.com/ImmediatePlatform/MediatorBenchmarks.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- No dependencies.
-
net8.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages (3)
Showing the top 3 NuGet packages that depend on Immediate.Handlers:
| Package | Downloads |
|---|---|
|
Immediate.Validations
Source generated validations for Immediate.Handlers parameters. |
|
|
Immediate.Apis
A source generator to bind Immediate.Handlers handlers to minimal APIs. |
|
|
Immediate.Cache
A collection of classes that simplify caching responses from Immediate.Handlers handlers. |
GitHub repositories (1)
Showing the top 1 popular GitHub repositories that depend on Immediate.Handlers:
| Repository | Stars |
|---|---|
|
ChilliCream/graphql-platform
Welcome to the home of the Hot Chocolate GraphQL server for .NET, the Strawberry Shake GraphQL client for .NET and Nitro the awesome Monaco based GraphQL IDE.
|
| Version | Downloads | Last Updated |
|---|---|---|
| 3.6.0 | 0 | 5/5/2026 |
| 3.5.1 | 36 | 5/4/2026 |
| 3.5.0 | 60 | 5/3/2026 |
| 3.4.0 | 4,630 | 3/26/2026 |
| 3.3.0 | 4,292 | 2/25/2026 |
| 3.2.0 | 4,542 | 2/9/2026 |
| 3.1.0 | 11,884 | 10/31/2025 |
| 3.1.0-preview.1 | 231 | 8/27/2025 |
| 3.0.0 | 6,755 | 8/22/2025 |
| 2.2.0 | 10,842 | 6/8/2025 |
| 2.1.0 | 38,060 | 4/14/2025 |
| 2.0.0 | 29,032 | 11/13/2024 |
| 1.7.1 | 687 | 11/13/2024 |
| 1.7.0 | 1,902 | 10/12/2024 |
| 1.6.1 | 1,538 | 9/10/2024 |
| 1.6.0 | 347 | 9/9/2024 |
| 1.5.0 | 3,751 | 7/13/2024 |
| 1.4.0 | 4,920 | 5/4/2024 |
| 1.3.1 | 741 | 4/8/2024 |
| 1.3.0 | 683 | 3/25/2024 |