Skip to content

Repository files navigation

Immediate.Handlers

NuGetGitHub releaseGitHub licenseGitHub issuesGitHub issues-closedGitHub ActionsCoverage Status

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

dotnet add package Immediate.Handlers

Using Immediate.Handlers

Creating Handlers

Create a Handler by adding the following code:

[Handler]publicsealedpartialclassGetUsersQuery(UsersServiceusersService){publicrecordQuery;privateValueTask<IEnumerable<User>>HandleAsync(Query_,CancellationTokentoken){returnusersService.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:

publicclassConsumer(GetUsersQuery.Handlerhandler){publicasyncTaskConsumer(CancellationTokentoken){varresponse=awaithandler.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]publicsealedpartialclassCreateUserCommand(UsersServiceusersService){publicrecordCommand(stringEmail);privateasyncValueTaskHandleAsync(Commandcommand,CancellationTokentoken){awaitusersService.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>.

publicclassConsumer(IHandler<Query,IEnumerable<User>>handler){publicasyncTaskConsumer(CancellationTokentoken){varresponse=awaithandler.HandleAsync(new(),token);// do something with response}}

Creating Behaviors

Create a behavior by implementing the Immediate.Handlers.Shared.Behaviors<,> class, as so:

publicsealedclassLoggingBehavior<TRequest,TResponse>(ILogger<LoggingBehavior<TRequest,TResponse>>logger):Behavior<TRequest,TResponse>{publicoverrideasyncValueTask<TResponse>HandleAsync(TRequestrequest,CancellationTokencancellationToken){logger.LogInformation("LoggingBehavior.Enter");varresponse=awaitNext(request,cancellationToken);logger.LogInformation("LoggingBehavior.Exit");returnresponse;}}

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<,>))]publicstaticclassGetUsersQuery{// ..}
  • Common behavior pipelines can be defined by applying a [Behaviors] attribute another attribute, as shown here:
[Behaviors(typeof(ValidationBehavior<,>),typeof(TransactionBehavior<,>))]publicsealedclassDefaultBehaviorsAttribute: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:

publicsealedclassLoggingBehavior<TRequest,TResponse>:Behavior<TRequest,TResponse>whereTRequest:IRequestConstraintwhereTResponse: 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 application identifier. By default, this is the short form of the assembly name. For example:

  • For a project named Web, it will be services.AddWebHandlers()
  • For a project named Application.Web, it will be services.AddApplicationWebHandlers()

However, this name can be overridden using [assembly: ImmediateAssemblyIdentifierAttribute("SomeIdentifier")].

Calling this AddXxxHandlers() method will register all classes in the assembly marked with [Handler].

Behavior dependencies are registered automatically alongside each handler when AddXxxHandlers() is called.

Tags

Assigns string tags to the registration. When AddXxxHandlers is called with tag arguments, only registrations that share at least one tag (or registrations with no tags) are included.

[Handler(Tags=["worker","background"])]publicsealedclassBackgroundWorker{}

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]publicstaticpartialclassStreamItems{publicrecordQuery(intCount);privatestaticasyncIAsyncEnumerable<int>HandleAsync(Queryquery,[EnumeratorCancellation]CancellationTokentoken){for(vari=0;i<query.Count;i++){awaitTask.Yield();yieldreturni;}}}

The generated StreamItems.Handler implements IStreamingHandler<StreamItems.Query, int>, allowing consumers to use either the concrete handler or the interface abstraction:

publicclassConsumer(IStreamingHandler<StreamItems.Query,int>handler){publicasyncTaskConsumeAsync(CancellationTokentoken){awaitforeach(variteminhandler.HandleAsync(new(5),token))Console.WriteLine(item);}}

Streaming Behavior

Create a streaming pipeline behavior by extending StreamingBehavior<TRequest, TResponse>:

publicclassLoggingBehavior<TRequest,TResponse>(ILogger<LoggingBehavior<TRequest,TResponse>>logger):StreamingBehavior<TRequest,TResponse>{publicoverrideasyncIAsyncEnumerable<TResponse>HandleAsync(TRequestrequest,[EnumeratorCancellation]CancellationTokencancellationToken){logger.LogInformation("LoggingBehavior.Enter");awaitforeach(variteminNext(request,cancellationToken))yieldreturnitem;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.

About

Source Generated implementation of the Mediator pattern

Topics

Resources

Stars

200 stars

Watchers

4 watching

Forks

Releases

Sponsor this project

Used by

Contributors

Languages