Tooark.Mediator
4.7.0
dotnet add package Tooark.Mediator --version 4.7.0
NuGet\Install-Package Tooark.Mediator -Version 4.7.0
<PackageReference Include="Tooark.Mediator" Version="4.7.0" />
<PackageVersion Include="Tooark.Mediator" Version="4.7.0" />
<PackageReference Include="Tooark.Mediator" />
paket add Tooark.Mediator --version 4.7.0
#r "nuget: Tooark.Mediator, 4.7.0"
#:package Tooark.Mediator@4.7.0
#addin nuget:?package=Tooark.Mediator&version=4.7.0
#tool nuget:?package=Tooark.Mediator&version=4.7.0
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
- Installation
- Configuration
- Components
- Usage Examples
- Dependencies
- Contributing
- Help & Security
- Support
- License
π 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 ofIMediator.
Dependency injection
TooarkDependencyInjection.AddTooarkMediator(IServiceCollection, params Assembly[])TooarkDependencyInjection.AddTooarkMediator(IServiceCollection, Action<MediatorOptions>, params Assembly[])TooarkDependencyInjection.AddTooarkMediatorBehavior<TBehavior>(IServiceCollection)TooarkDependencyInjection.AddTooarkMediatorBehavior(IServiceCollection, Type)
Options
MediatorOptionsNotifyPublishStrategy(default:ENotifyStrategy.ParallelWhenAll)- Registered through the Options pattern: multiple
AddTooarkMediatorcalls compose the configuration in registration order MediatorreceivesIOptions<MediatorOptions>. To configure outsideAddTooarkMediator, useservices.Configure<MediatorOptions>(...)β registeringMediatorOptionsdirectly in the container has no effect
Publishing strategies
ENotifyStrategy.ParallelWhenAll(default): starts every handler and waits for all of them to complete withTask.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.EntityFrameworkCorepackage 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:
- π GitHub Sponsors
- β Ko-fi
Every contribution helps keep the project maintained and improving. Thank you! π
π License
This project is licensed under the BSD 3-Clause License.
| 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 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. |
-
net10.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.12)
- Microsoft.Extensions.Options (>= 10.0.12)
- Tooark.Exceptions (>= 4.7.0)
- Tooark.Mediator.Abstractions (>= 4.7.0)
-
net8.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.2)
- Microsoft.Extensions.Options (>= 8.0.2)
- Tooark.Exceptions (>= 4.7.0)
- Tooark.Mediator.Abstractions (>= 4.7.0)
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 | 270 | 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 |