Tooark.Mediator 4.7.0

dotnet add package Tooark.Mediator --version 4.7.0
                    
NuGet\Install-Package Tooark.Mediator -Version 4.7.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Tooark.Mediator" Version="4.7.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Tooark.Mediator" Version="4.7.0" />
                    
Directory.Packages.props
<PackageReference Include="Tooark.Mediator" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Tooark.Mediator --version 4.7.0
                    
#r "nuget: Tooark.Mediator, 4.7.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Tooark.Mediator@4.7.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Tooark.Mediator&version=4.7.0
                    
Install as a Cake Addin
#tool nuget:?package=Tooark.Mediator&version=4.7.0
                    
Install as a Cake Tool

Tooark.Mediator

Library with a Mediator implementation for .NET projects, focused on CQRS/CQS with low coupling between layers.

🌍 Languages: πŸ‡ΊπŸ‡Έ English (this file) Β· πŸ‡§πŸ‡· PortuguΓͺs


πŸ“‘ Contents


πŸ“– Overview

The Tooark.Mediator package provides:

  • a concrete implementation of IMediator;
  • automatic handler registration by assembly;
  • a behavior pipeline for cross-cutting concerns;
  • a configurable notification publishing strategy;
  • integration with Microsoft.Extensions.DependencyInjection.

πŸ”§ Installation

dotnet add package Tooark.Mediator

βš™οΈ Configuration

using Tooark.Mediator.Injections;

builder.Services.AddTooarkMediator(typeof(Program).Assembly);

The mediator options can also be configured:

using Tooark.Mediator.Enums;
using Tooark.Mediator.Injections;

builder.Services.AddTooarkMediator(options =>
{
  options.NotifyPublishStrategy = ENotifyStrategy.Sequential;
}, typeof(Program).Assembly);

Recommendation: always pass the assemblies explicitly (e.g. typeof(Program).Assembly). Without assemblies, the calling assembly is scanned as a fallback β€” it works for the common case, but the explicit form is immune to refactorings that move the call to another project. Open generic classes are skipped by the scan (dispatch does not support open generics).


πŸ“¦ Components

Main class

  • Mediator: implementation of IMediator.

Dependency injection

  • TooarkDependencyInjection.AddTooarkMediator(IServiceCollection, params Assembly[])
  • TooarkDependencyInjection.AddTooarkMediator(IServiceCollection, Action<MediatorOptions>, params Assembly[])
  • TooarkDependencyInjection.AddTooarkMediatorBehavior<TBehavior>(IServiceCollection)
  • TooarkDependencyInjection.AddTooarkMediatorBehavior(IServiceCollection, Type)

Options

  • MediatorOptions
    • NotifyPublishStrategy (default: ENotifyStrategy.ParallelWhenAll)
    • Registered through the Options pattern: multiple AddTooarkMediator calls compose the configuration in registration order
    • Mediator receives IOptions<MediatorOptions>. To configure outside AddTooarkMediator, use services.Configure<MediatorOptions>(...) β€” registering MediatorOptions directly in the container has no effect

Publishing strategies

  • ENotifyStrategy.ParallelWhenAll (default): starts every handler and waits for all of them to complete with Task.WhenAll. Best latency when the handlers are independent. Every handler is started even if one fails to start, and the first failure is propagated to the caller.
  • ENotifyStrategy.Sequential: starts each handler only after the previous one completes, in registration order. If a handler fails, the following ones do not run (fail-fast). Use it when the order of side effects matters or the handlers share resources that are not thread-safe.

Behavior pipeline

IPipelineBehavior<TRequest, TResponse> wraps the handler execution, allowing cross-cutting concerns β€” validation, logging, transaction, caching, authorization β€” to be handled without repeating them in every handler. Each behavior decides whether to invoke the next step: not invoking it interrupts the pipeline (short-circuit) and the behavior's own response is returned to the caller.

Behaviors apply only to requests; notifications do not go through the pipeline. The handler is resolved before the chain is built, so Handler.NotFound still fails before any behavior runs. With no behaviors registered, dispatch remains the direct invocation of the handler.

The CancellationToken is a required parameter of the next step β€” pass along the received token to propagate cancellation, or pass a linked token to apply your own limit.

An open generic behavior can restrict which requests it applies to through its type constraint. A behavior declared with where TRequest : ICommand<TResponse> wraps commands only, and the container skips it when dispatching queries β€” with no need for a runtime type check. The same applies to constraints on the application's own interfaces.

Registration validation

A request is processed by a single handler. If the scan or manual registration results in more than one handler for the same request, AddTooarkMediator throws InternalServerErrorException with the Handler.Duplicated code, identifying the request and the conflicting handlers. Notifications keep accepting as many handlers as are registered.

Dispatch performance

Dispatch uses generic wrappers in a static cache: reflection happens only on the first call for each message type. Exceptions thrown by handlers reach the caller directly (no TargetInvocationException).

Supported handlers

  • IRequestHandler<TRequest, TResponse>
  • ICommandHandler<TCommand, TResponse>
  • ICommandHandler<TCommand>
  • IQueryHandler<TQuery, TResponse>
  • INotifyHandler<TNotify>

Supported behaviors

  • IPipelineBehavior<TRequest, TResponse>

Handlers live in the Tooark.Mediator.Handlers namespace and behaviors in Tooark.Mediator.Behaviors.


πŸ“ Usage Examples

CQRS example

using Tooark.Mediator.Abstractions;
using Tooark.Mediator.Handlers;

public sealed record CreateUserCommand(string Name) : ICommand<Guid>;

public sealed class CreateUserCommandHandler : ICommandHandler<CreateUserCommand, Guid>
{
  public Task<Guid> HandleAsync(CreateUserCommand request, CancellationToken cancellationToken = default)
  {
    return Task.FromResult(Guid.NewGuid());
  }
}

public sealed record GetUserByIdQuery(Guid Id) : IQuery<string>;

public sealed class GetUserByIdQueryHandler : IQueryHandler<GetUserByIdQuery, string>
{
  public Task<string> HandleAsync(GetUserByIdQuery request, CancellationToken cancellationToken = default)
  {
    return Task.FromResult($"User {request.Id}");
  }
}

Using IMediator

using Tooark.Mediator.Abstractions;

public sealed class UsersService(IMediator mediator)
{
  public Task<Guid> CreateAsync(string name, CancellationToken cancellationToken)
  {
    return mediator.SendAsync(new CreateUserCommand(name), cancellationToken);
  }

  public Task<string> GetAsync(Guid id, CancellationToken cancellationToken)
  {
    return mediator.SendAsync(new GetUserByIdQuery(id), cancellationToken);
  }
}

Publishing a notification

using Tooark.Mediator.Abstractions;
using Tooark.Mediator.Handlers;

public sealed record UserCreatedNotify(Guid UserId) : INotify;

public sealed class UserCreatedNotifyHandler : INotifyHandler<UserCreatedNotify>
{
  public Task HandleAsync(UserCreatedNotify notification, CancellationToken cancellationToken = default)
  {
    Console.WriteLine($"User created: {notification.UserId}");
    return Task.CompletedTask;
  }
}

await mediator.PublishAsync(new UserCreatedNotify(Guid.NewGuid()), cancellationToken);

Pipeline behavior example

Open generic behavior, applied to every request:

using Tooark.Mediator.Abstractions;
using Tooark.Mediator.Behaviors;

public sealed class LoggingBehavior<TRequest, TResponse>(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
  : IPipelineBehavior<TRequest, TResponse>
  where TRequest : IRequest<TResponse>
{
  public async Task<TResponse> HandleAsync(
    TRequest request,
    RequestHandlerDelegate<TResponse> next,
    CancellationToken cancellationToken = default)
  {
    logger.LogInformation("Starting {Request}", typeof(TRequest).Name);

    var response = await next(cancellationToken);

    logger.LogInformation("Completed {Request}", typeof(TRequest).Name);

    return response;
  }
}

Closed behavior, applied to a specific request, which interrupts the pipeline when the request is invalid:

using Tooark.Exceptions;
using Tooark.Mediator.Behaviors;
using Tooark.Validations;

public sealed class CreateUserValidationBehavior : IPipelineBehavior<CreateUserCommand, Guid>
{
  public Task<Guid> HandleAsync(
    CreateUserCommand request,
    RequestHandlerDelegate<Guid> next,
    CancellationToken cancellationToken = default)
  {
    var validation = new Validation()
      .IsNotNullOrEmpty(request.Name, nameof(request.Name), "User.NameRequired");

    // Short-circuit: the handler is not executed
    if (!validation.IsValid)
    {
      throw new BadRequestException(validation);
    }

    return next(cancellationToken);
  }
}

Unit of work behavior, moving Entity Framework's SaveChanges into the pipeline β€” handlers only describe the changes and persistence happens once, at the end:

using Tooark.Mediator.Abstractions;
using Tooark.Mediator.Behaviors;

public sealed class UnitOfWorkBehavior<TRequest, TResponse>(AppDbContext context)
  : IPipelineBehavior<TRequest, TResponse>
  where TRequest : ICommand<TResponse>
{
  public async Task<TResponse> HandleAsync(
    TRequest request,
    RequestHandlerDelegate<TResponse> next,
    CancellationToken cancellationToken = default)
  {
    var response = await next(cancellationToken);

    // An exception from the handler prevents this line: nothing is persisted
    await context.SaveChangesAsync(cancellationToken);

    return response;
  }
}

The where TRequest : ICommand<TResponse> constraint keeps queries out of the pipeline β€” without it, every read would call SaveChanges with nothing to persist. A single SaveChangesAsync is already atomic, since Entity Framework wraps the batch in a transaction; an explicit BeginTransaction is only needed when the handler persists more than once or combines the DbContext with another transactional resource.

The example above illustrates the pattern. For Entity Framework Core, the Tooark.Mediator.EntityFrameworkCore package ships that behavior ready-made, with nested command handling and an explicit transaction strategy.

With that behavior registered, the handler does not touch persistence:

public sealed class CreateUserHandler(AppDbContext context) : ICommandHandler<CreateUserCommand, Guid>
{
  public Task<Guid> HandleAsync(CreateUserCommand request, CancellationToken cancellationToken = default)
  {
    var user = new User(request.Name);

    context.Users.Add(user);

    return Task.FromResult(user.Id);
  }
}

Registration, in the order they must run β€” the first registered is the outermost:

using Tooark.Mediator.Injections;

builder.Services.AddTooarkMediator(typeof(Program).Assembly);
builder.Services.AddTooarkMediatorBehavior(typeof(LoggingBehavior<,>));
builder.Services.AddTooarkMediatorBehavior<CreateUserValidationBehavior>();
builder.Services.AddTooarkMediatorBehavior(typeof(UnitOfWorkBehavior<,>));

Validation comes before the unit of work: it makes no sense to prepare persistence and then reject the request.

Behaviors are not discovered by the assembly scan: the execution order is semantic and the order returned by the scan is not guaranteed. Registration is always explicit.

Two points of attention with the unit of work in the pipeline. A command dispatched from within another command persists in the middle of the outer one's operation, which persists again at the end β€” avoid nesting or handle reentrancy. And notifications do not go through the pipeline: their handlers run inside the command handler, therefore before SaveChanges, and whatever they write to the context is persisted together.


πŸ“‹ Dependencies

Package Version Description
Tooark.Exceptions 4.x Exceptions (e.g. BadRequestException)
Tooark.Mediator.Abstractions 4.x Base contracts of the Mediator pattern
Microsoft.Extensions.DependencyInjection.Abstractions 8.x/10.x Dependency injection abstractions
Microsoft.Extensions.Options 8.x/10.x Options pattern for MediatorOptions

🀝 Contributing

Contributions are welcome! Start with CONTRIBUTING.md β€” it covers the development workflow, the coding and commit conventions and the pull request checklist. Bugs and feature requests go through the issue templates of the Tooark repository.

By participating you agree to the Code of Conduct.


πŸ†˜ Help & Security

  • ❓ Questions, bugs, feature ideas β€” see SUPPORT.md for the right channel
  • πŸ”’ Security vulnerabilities β€” do not open a public issue; follow SECURITY.md

πŸ’– Support

If Tooark helps your projects, consider supporting its development:

Every contribution helps keep the project maintained and improving. Thank you! πŸ™


πŸ“„ License

This project is licensed under the BSD 3-Clause License.

Product 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 was computed.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on Tooark.Mediator:

Package Downloads
Tooark

Package with all Tooark resources for .NET applications.

Tooark.Mediator.EntityFrameworkCore

Library that moves Entity Framework Core persistence into the Tooark.Mediator pipeline, keeping handlers free of SaveChanges.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
4.7.0 277 9/30/2026
4.6.0 160 9/29/2026
4.5.0 124 9/29/2026
4.4.0 125 9/28/2026
4.3.0 134 9/26/2026
4.2.1 133 9/25/2026
4.2.0 135 9/20/2026
4.1.0 130 9/18/2026
4.0.1 174 8/25/2026
4.0.0 163 8/25/2026
3.3.6 105 9/18/2026
3.3.5 123 8/25/2026
3.3.4 131 8/12/2026
3.3.3 145 7/27/2026
3.3.2 303 6/11/2026
3.3.1 153 6/6/2026
3.3.0 160 4/17/2026