AsyncMediator 3.1.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package AsyncMediator --version 3.1.0
                    
NuGet\Install-Package AsyncMediator -Version 3.1.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="AsyncMediator" Version="3.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="AsyncMediator" Version="3.1.0" />
                    
Directory.Packages.props
<PackageReference Include="AsyncMediator" />
                    
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 AsyncMediator --version 3.1.0
                    
#r "nuget: AsyncMediator, 3.1.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 AsyncMediator@3.1.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=AsyncMediator&version=3.1.0
                    
Install as a Cake Addin
#tool nuget:?package=AsyncMediator&version=3.1.0
                    
Install as a Cake Tool

AsyncMediator

A lightweight, high-performance mediator for .NET 9/10. Zero dependencies. Minimal allocations.

Install-Package AsyncMediator

Quick Start

1. Wire Up DI

services.AddScoped<IMediator>(sp => new Mediator(
    type => sp.GetServices(type),
    type => sp.GetRequiredService(type)));

services.AddTransient<ICommandHandler<CreateOrderCommand>, CreateOrderHandler>();
services.AddTransient<IEventHandler<OrderCreatedEvent>, SendConfirmationEmailHandler>();
services.AddTransient<IQuery<OrderSearchCriteria, List<Order>>, OrderQuery>();

2. Define a Command

public record CreateOrderCommand(Guid CustomerId, List<OrderItem> Items) : ICommand;

public class CreateOrderHandler(IMediator mediator, IOrderRepository repo)
    : CommandHandler<CreateOrderCommand>(mediator)
{
    protected override Task Validate(ValidationContext ctx, CancellationToken cancellationToken)
    {
        if (Command.Items.Count == 0)
            ctx.AddError(nameof(Command.Items), "Order must have items");
        return Task.CompletedTask;
    }

    protected override async Task<ICommandWorkflowResult> DoHandle(ValidationContext ctx, CancellationToken cancellationToken)
    {
        var order = await repo.Create(Command.CustomerId, Command.Items, cancellationToken);
        Mediator.DeferEvent(new OrderCreatedEvent(order.Id));
        return CommandWorkflowResult.Ok();
    }
}

3. Send It

var result = await mediator.Send(new CreateOrderCommand(customerId, items));
if (!result.Success)
    return BadRequest(result.ValidationResults);

// With cancellation support (e.g., from HttpContext.RequestAborted)
var result = await mediator.Send(command, cancellationToken);

Queries

// With criteria
public record OrderSearchCriteria(Guid? CustomerId, DateOnly? Since);

public class OrderQuery(IOrderRepository repo) : IQuery<OrderSearchCriteria, List<Order>>
{
    public Task<List<Order>> Query(OrderSearchCriteria c, CancellationToken cancellationToken = default) =>
        repo.Search(c.CustomerId, c.Since, cancellationToken);
}

var orders = await mediator.Query<OrderSearchCriteria, List<Order>>(criteria);

// Without criteria
public class CountryLookup(ICountryRepository repo) : ILookupQuery<List<Country>>
{
    public Task<List<Country>> Query(CancellationToken cancellationToken = default) =>
        repo.GetAll(cancellationToken);
}

var countries = await mediator.LoadList<List<Country>>();

Events

Events are deferred during command execution and published after DoHandle completes.

public record OrderCreatedEvent(Guid OrderId) : IDomainEvent;

public class SendConfirmationEmailHandler(IEmailService email) : IEventHandler<OrderCreatedEvent>
{
    public async Task Handle(OrderCreatedEvent e, CancellationToken cancellationToken = default) =>
        await email.SendOrderConfirmation(e.OrderId, cancellationToken);
}

Multiple handlers per event are supported. They execute in DI registration order.

Pipeline Behaviors (Cross-Cutting Concerns)

Pipeline behaviors wrap handler execution for cross-cutting concerns. No overhead when no behaviors are registered.

Use behaviorFactory to resolve open generic behaviors from your DI container. This applies behaviors to ALL commands automatically:

// Register open generic behaviors
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));

// Use behaviorFactory to resolve behaviors from DI
services.AddScoped<IMediator>(sp => new Mediator(
    type => sp.GetServices(type),
    type => sp.GetRequiredService(type),
    behaviorFactory: type => sp.GetServices(type)));

Option 2: Explicit Registration

For specific behaviors on specific commands:

services.AddScoped<IMediator>(sp => new Mediator(
    type => sp.GetServices(type),
    type => sp.GetRequiredService(type),
    behaviors: [
        new LoggingBehavior<CreateOrderCommand, ICommandWorkflowResult>(),
        new MetricsBehavior<CreateOrderCommand, ICommandWorkflowResult>()
    ]));

Example: Logging Behavior

public class LoggingBehavior<TRequest, TResponse>(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
    : IPipelineBehavior<TRequest, TResponse>
{
    public async Task<TResponse> Handle(
        TRequest request,
        RequestHandlerDelegate<TResponse> next,
        CancellationToken cancellationToken)
    {
        logger.LogInformation("Handling {RequestType}", typeof(TRequest).Name);
        var sw = Stopwatch.StartNew();
        var response = await next();
        logger.LogInformation("Handled {RequestType} in {ElapsedMs}ms", typeof(TRequest).Name, sw.ElapsedMilliseconds);
        return response;
    }
}

Example: Validation with DataAnnotations

Use built-in System.ComponentModel.DataAnnotations:

public record CreateOrderCommand(
    [property: Required, MinLength(1)] Guid CustomerId,
    [property: Required, MinLength(1)] List<OrderItem> Items) : ICommand;

public class ValidationBehavior<TRequest> : IPipelineBehavior<TRequest, ICommandWorkflowResult>
    where TRequest : ICommand
{
    public Task<ICommandWorkflowResult> Handle(
        TRequest request,
        RequestHandlerDelegate<ICommandWorkflowResult> next,
        CancellationToken cancellationToken)
    {
        var context = new System.ComponentModel.DataAnnotations.ValidationContext(request);
        var results = new List<ValidationResult>();

        if (!Validator.TryValidateObject(request, context, results, validateAllProperties: true))
        {
            return Task.FromResult<ICommandWorkflowResult>(
                new CommandWorkflowResult(results));
        }

        return next();
    }
}

Behaviors execute in registration order, wrapping around the handler like middleware. Each behavior can:

  • Execute logic before/after the handler
  • Short-circuit by not calling next()
  • Catch and handle exceptions

Transactions

TransactionScope is opt-in for performance. Override when ACID guarantees are needed:

public class TransferFundsHandler(IMediator mediator) : CommandHandler<TransferFundsCommand>(mediator)
{
    protected override bool UseTransactionScope => true;  // Enables TransactionScope

    protected override async Task<ICommandWorkflowResult> DoHandle(ValidationContext ctx, CancellationToken cancellationToken)
    {
        await DebitAccount(Command.FromAccount, Command.Amount, cancellationToken);
        await CreditAccount(Command.ToAccount, Command.Amount, cancellationToken);
        Mediator.DeferEvent(new FundsTransferredEvent(Command.FromAccount, Command.ToAccount));
        return CommandWorkflowResult.Ok();
    }
}

Performance

Operation Latency Memory
Command (success) ~170 ns ~200 B
Command (10 concurrent) ~1.7 μs ~2 KB
Query ~150 ns ~200 B

87% faster and 83% less memory than v2.x.

Docs

Cancellation Support

All async operations support cancellation tokens for graceful shutdown and timeout handling:

// In ASP.NET Core controllers
public async Task<IActionResult> CreateOrder(CreateOrderCommand command, CancellationToken cancellationToken)
{
    var result = await _mediator.Send(command, cancellationToken);
    return result.Success ? Ok() : BadRequest(result.ValidationResults);
}

// With timeout
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var result = await mediator.Send(command, cts.Token);

// Execute deferred events with cancellation
await mediator.ExecuteDeferredEvents(cancellationToken);

Breaking Changes (v3.0)

  • Requires .NET 9 or .NET 10
  • CancellationToken parameter added to all async interfaces (see Migration Guide)
  • TransactionScope now opt-in (override UseTransactionScope => true)
  • Removed HandlerOrderAttribute (use DI registration order)
  • ICommandWorkflowResult.ValidationResults is now List<T>

License

MIT

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

    • No dependencies.
  • net9.0

    • No dependencies.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on AsyncMediator:

Package Downloads
AsyncMediator.Extensions.DependencyInjection

Setup helpers for configuring AsyncMediator with Microsoft Dependency Injection.

AsyncMediator.Extensions.Autofac

Setup helpers for configuring AsyncMediator with Autofac.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.1.2 163 12/28/2025
3.1.1 143 12/28/2025
3.1.0 152 12/27/2025
3.0.0 140 12/27/2025
2.1.0 25,759 11/8/2020
2.0.0 39,040 11/16/2015
1.0.2 1,743 10/22/2015
1.0.1 2,776 8/27/2015
1.0.0 1,718 8/26/2015

v3.1.0 - Added pipeline behaviors with behaviorFactory for DI integration, expression-compiled delegates for event publishing. See PIPELINE.md.