Open Source CQRS .NET Native

Cortex.Mediator

A high-performance Mediator pattern implementation built for CQRS systems. Centralize commands, queries, and notifications—with pluggable pipeline behaviors.

CQRS

First-class

0 Reflection

At Runtime

100%

Open Source
// Send a command through the mediator
var result = await mediator
  .SendCommandAsync<
    CreateOrderCommand,
    OrderResult>(
    new CreateOrderCommand
    {
      ProductId = "SKU-42",
      Quantity = 3
    });
// Publish a notification
await mediator.PublishAsync(
  new OrderCreatedNotification(result.Id));
Core Building Blocks

Commands · Queries · Notifications

Cortex.Mediator separates concerns cleanly: commands change state, queries read data, and notifications broadcast events—each with its own handler and optional pipeline behaviors.

Commands

Mutate system state. Each command implements ICommand<TResult> and is handled by a dedicated ICommandHandler.

public record CreateOrder
  : ICommand<OrderResult>
{
  public string ProductId { get; init; }
  public int Quantity { get; init; }
}

Queries

Read data without side-effects. Implement IQuery<TResult> and a matching IQueryHandler.

public record GetOrderById
  : IQuery<OrderDto>
{
  public Guid OrderId { get; init; }
}

Notifications

Fan-out events to multiple handlers. Implement INotification and one or more INotificationHandlers.

public record OrderCreated
  : INotification
{
  public Guid OrderId { get; init; }
}
Pipeline Architecture

How Requests Flow Through the Mediator

Every command or query passes through configurable pipeline behaviors before reaching its handler—giving you hooks for validation, logging, caching, and transactions.

Client
IMediator
Pipeline
Behaviors
Handler
Validation

Run FluentValidation rules on any command or query before it reaches the handler. Invalid requests are rejected early.

Logging

Automatic structured logging for every request—duration, success/failure, and exception details without boilerplate code.

Transactions

Wrap command handlers in a transaction scope to guarantee atomicity. Rollback happens automatically on failure.

Caching

Cache query results with a pipeline behavior. Subsequent identical queries return instantly from cache.

Exception Handling

Centralize exception handling across your application. Map exceptions to user-friendly error responses consistently.

Request Processors

Pre- and post-process requests for cross-cutting concerns like auditing, enrichment, or metrics collection.

Architecture Patterns

CQRS & Vertical Slice,
Out of the Box

Cortex.Mediator is designed around CQRS principles. Pair it with Vertical Slice Architecture to organize features by capability rather than technical layers.

CQRS Separation

Commands and queries are handled by separate handler types with distinct pipeline behavior chains.

Vertical Slices

Organize code by feature—each slice contains its own command, handler, validator, and response type.

Streaming Queries

Return IAsyncEnumerable from query handlers to stream large result sets without buffering.

FluentValidation

Built-in integration with FluentValidation for declarative, strongly-typed request validation.

Quick Start

Up & Running in Minutes

Register the mediator in your DI container, define a command + handler, and send it. That's it—no XML, no configuration files, no ceremony.

  1. 1
    Installdotnet add package Cortex.Mediator
  2. 2
    Register — Add services.AddCortexMediator() in Startup.
  3. 3
    Define — Create a command implementing ICommand<T>.
  4. 4
    Handle — Write an ICommandHandler<TCommand, TResult>.
  5. 5
    Send — Call mediator.SendCommandAsync(…).
// Command
public record CreateUser(string Name)
  : ICommand<Guid>;
// Handler
public class CreateUserHandler
  : ICommandHandler<CreateUser, Guid>
{
  public async Task<Guid> Handle(
    CreateUser cmd, CancellationToken ct)
  {
    var id = Guid.NewGuid();
    // persist user…
    return id;
  }
}
// Usage
var userId = await mediator
  .SendCommandAsync<CreateUser, Guid>(
    new CreateUser("Alice"));
Real-World Example

Build an E-Commerce Backend

See how Cortex.Mediator powers a complete order processing flow—from placing an order, to validation, persistence, and notification broadcasting.

Place Order

Client sends a PlaceOrderCommand via the mediator.

Validate

FluentValidation behavior checks stock, pricing, and customer eligibility.

Persist

Handler saves the order inside a transactional pipeline behavior.

Notify

An OrderPlaced notification fans out to email, analytics, and inventory handlers.

Simplify Your Architecture Today

Stop scattering cross-cutting concerns across controllers and services. Let Cortex.Mediator centralize your command, query, and notification logic.