Home

Awesome

Immediate.Handlers

NuGet GitHub release GitHub license GitHub issues GitHub issues-closed GitHub Actions

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

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 static partial class GetUsersQuery
{
    public record Query;

    private static ValueTask<IEnumerable<User>> HandleAsync(
        Query _,
        UsersService usersService,
        CancellationToken token
	)
    {
        return usersService.GetUsers();
    }
}

This will automatically create a new class, GetUsersQuery.Handler, which encapsulates the following:

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 static partial class CreateUserCommand
{
    public record Command(string Email);

    private static async ValueTask HandleAsync( 
        Command command,
        UsersService usersService,
        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;
	}
}

This can be registered assembly-wide using:

[assembly: Behaviors(
	typeof(LoggingBehavior<,>)
)]

or on an individual handler using:

[Handler]
[Behavior(
	typeof(LoggingBehavior<,>)
)]
public static class GetUsersQuery
{
	// ..
}

Once added to the pipeline, the behavior will be called as part of the pipeline to handle a request.

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.

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.

This registers all behaviors referenced in any [Behaviors] attribute.

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

All performance benchmarks reported use the following environment:

// * Summary *

BenchmarkDotNet v0.14.0, Windows 11 (10.0.22631.4317/23H2/2023Update/SunValley3)
12th Gen Intel Core i7-12700H, 1 CPU, 20 logical and 14 physical cores
.NET SDK 9.0.100
  [Host]     : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2
  DefaultJob : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2

Benchmarks.Simple

This benchmark tests the various mediator implementations with a single request/response handler.

MethodMeanErrorRatioRankAllocated
SendRequest_Baseline0.6618 ns0.0127 ns1.001-
SendRequest_IHandler14.0497 ns0.0753 ns21.232-
SendRequest_ImmediateHandler14.9493 ns0.0818 ns22.593-
SendRequest_Mediator22.0218 ns0.0684 ns33.284-
SendRequest_IMediator26.8625 ns0.1428 ns40.605-
SendRequest_MediatR47.5135 ns0.4161 ns71.816192 B

Benchmarks.Large

This benchmark tests the various mediator implementations in the face of 999 request/response handlers.

MethodMeanErrorRatioRankAllocated
SendRequest_Baseline0.6257 ns0.0202 ns1.001-
SendRequest_ImmediateHandler11.2358 ns0.0395 ns17.972-
SendRequest_IHandler14.0575 ns0.0652 ns22.493-
SendRequest_Mediator22.0874 ns0.0534 ns35.334-
SendRequest_MediatR48.3577 ns0.2402 ns77.355192 B
SendRequest_IMediator420.2067 ns4.5092 ns672.176-

Benchmarks.Behaviors

This benchmark tests a more realistic scenario of using 1 behavior and 1 service.

MethodMeanErrorRatioRankAllocated
SendRequest_Baseline47.83 ns0.160 ns1.00140 B
SendRequest_ImmediateHandler62.67 ns0.350 ns1.31240 B
SendRequest_IHandler63.59 ns0.218 ns1.33240 B
SendRequest_Mediator91.53 ns0.292 ns1.91340 B
SendRequest_IMediator100.73 ns0.396 ns2.11440 B
SendRequest_MediatR188.54 ns0.785 ns3.945560 B