Chatter.CQRS 0.12.0

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

<a name="chatter-cqrs"></a> Chatter.CQRS

A lightweight CQRS framework for .NET that dispatches Commands, Queries, and Events to their handlers via the mediator pattern.

Overview

Chatter.CQRS is the foundational module of the Chatter library suite. It implements Command Query Responsibility Segregation (CQRS) using an in-process mediator pattern: instead of calling handler classes directly, your code dispatches messages and the framework routes each one to the registered handler(s).

The module distinguishes three kinds of message, all of which derive from the IMessage marker interface:

  • Commands (ICommand) — instruct an aggregate to change state; dispatched to exactly one handler.
  • Queries (IQuery<T>) — retrieve a read model without mutating state; dispatched to exactly one handler that returns a result.
  • Events (IEvent) — announce that something happened; fanned out to zero or many handlers.

Handlers are discovered automatically by assembly scanning (powered by Scrutor) and registered into the standard Microsoft.Extensions.DependencyInjection container. Only closed handler types are scanned, and a discovered handler is registered only under the closed IMessageHandler<TMessage> / IQueryHandler<TQuery,TResult> interface(s) it implements, not under any other interface the handler class may implement (see the command registration contract below). An open-generic handler class is not discovered by the scan and must be registered manually. Commands additionally flow through an optional command pipeline of cross-cutting behaviors.

Installation

dotnet add package Chatter.CQRS

Getting Started

1. Register Chatter.CQRS with DI

The entry point is the AddChatterCqrs extension method on IServiceCollection. It scans the supplied assemblies for handlers and wires up the dispatchers. Several overloads control how handler assemblies are located:

using Microsoft.Extensions.DependencyInjection;

// Locate handler assemblies via marker types (the assembly each type lives in is scanned)
services.AddChatterCqrs(configuration, typeof(CreateOrderHandler), typeof(SomeOtherHandler));

// ...or pass explicit assemblies
services.AddChatterCqrs(configuration, typeof(Program).Assembly);

// ...or select assemblies by namespace/assembly-name with '*' and '?' wildcards
services.AddChatterCqrs(configuration, "MyApp.*");

// ...or use the full builder form with a command pipeline + assembly source filter
services.AddChatterCqrs(
    configuration,
    pipelineBuilder: pipeline => pipeline.WithBehavior(typeof(LoggingBehavior<>)),
    messageHandlerSourceBuilder: source => source.WithMarkerTypes(typeof(CreateOrderHandler)));

AddChatterCqrs returns an IChatterBuilder, which exposes the Services, Configuration, and AssemblySourceFilter used by other Chatter modules (such as the message brokers) to extend the registration.

2. Define a command and its handler

using Chatter.CQRS;
using Chatter.CQRS.Commands;
using Chatter.CQRS.Context;
using System.Threading.Tasks;

public class CreateOrder : ICommand
{
    public string CustomerId { get; set; }
    public decimal Total { get; set; }
}

public class CreateOrderHandler : IMessageHandler<CreateOrder>
{
    public Task Handle(CreateOrder message, IMessageHandlerContext context)
    {
        // ... change aggregate state
        return Task.CompletedTask;
    }
}

3. Dispatch the command

Inject IMessageDispatcher and dispatch:

public class OrdersController
{
    private readonly IMessageDispatcher _dispatcher;

    public OrdersController(IMessageDispatcher dispatcher)
        => _dispatcher = dispatcher;

    public Task Post(CreateOrder command)
        => _dispatcher.Dispatch(command);
}

Core Concepts

Messages

IMessage is the root marker interface. ICommand and IEvent both extend it. Queries use the separate IQuery / IQuery<T> markers.

Commands

A ICommand is dispatched through IMessageDispatcher to a single IMessageHandler<TCommand>. During scanning, command handlers are registered with a replace strategy, enforcing that a command resolves to exactly one handler.

Task Dispatch<TMessage>(TMessage message) where TMessage : IMessage;
Task Dispatch<TMessage>(TMessage message, IMessageHandlerContext messageHandlerContext) where TMessage : IMessage;

Queries and Read Models

A query implements IQuery<TResult>, where TResult is the read model returned. Query handlers implement IQueryHandler<TQuery, TResult> and are dispatched through IQueryDispatcher:

public class GetOrderById : IQuery<OrderReadModel>
{
    public string OrderId { get; set; }
}

public class GetOrderByIdHandler : IQueryHandler<GetOrderById, OrderReadModel>
{
    public Task<OrderReadModel> Handle(GetOrderById query, IQueryHandlerContext context)
        => Task.FromResult(new OrderReadModel(/* ... */));
}
public class OrdersService
{
    private readonly IQueryDispatcher _queries;
    public OrdersService(IQueryDispatcher queries) => _queries = queries;

    public Task<OrderReadModel> Get(string id)
        => _queries.Query(new GetOrderById { OrderId = id });
}

IQueryDispatcher offers overloads that take the query alone or with an explicit IQueryHandlerContext, and strongly-typed Query<TQuery, TResult> forms.

Query scanning discovers only closed handler types. An open-generic query handler — class MyHandler<TQuery, TResult> : IQueryHandler<TQuery, TResult> — is not discovered and must be registered manually after AddChatterCqrs:

services.AddTransient(typeof(IQueryHandler<,>), typeof(MyHandler<,>));

Events: Domain vs Integration

An IEvent is dispatched through the same IMessageDispatcher but is fanned out to all registered IMessageHandler<TEvent> handlers (event handlers are appended during scanning rather than replaced). Handlers are invoked sequentially.

  • A Domain Event is handled in-process within the originating domain.
  • An Integration Event is published outward to other services. Cross-service publishing requires broker infrastructure provided by the Chatter Message Brokers modules.
public class OrderCreated : IEvent
{
    public string OrderId { get; set; }
}

public class SendConfirmationEmail : IMessageHandler<OrderCreated>
{
    public Task Handle(OrderCreated message, IMessageHandlerContext context)
        => /* ... */ Task.CompletedTask;
}

Message Context

Every dispatch carries a context object that flows alongside the message through the pipeline and into handlers:

  • IMessageHandlerContext (concrete: MessageHandlerContext) is passed to message handlers and exposes a CancellationToken.
  • IQueryHandlerContext (concrete: QueryHandlerContext) is passed to query handlers.

Both implement IContainContext, which exposes a ContextContainer Container. The container is an extensible, type-keyed bag for attaching arbitrary contextual data:

public Task Handle(CreateOrder message, IMessageHandlerContext context)
{
    // store
    context.Container.Include(new TenantInfo("acme"));

    // retrieve
    var tenant = context.Container.Get<TenantInfo>();
    if (context.Container.TryGet<TenantInfo>(out var t)) { /* ... */ }

    // get-or-create helpers
    var settings = context.Container.GetOrNew<Settings>();

    return Task.CompletedTask;
}

A ContextContainer can be created with an inherited container, in which case lookups fall through to the parent. When you dispatch without supplying a context, MessageDispatcher creates a fresh MessageHandlerContext and seeds the container with the active IMessageDispatcher and IExternalDispatcher.

Dispatch

IMessageDispatcher is the unified entry point for both commands and events. Internally it resolves the correct IDispatchMessages implementation (CommandDispatcher for ICommand, EventDispatcher for IEvent) via the IMessageDispatcherProvider, based on the message type. IQueryDispatcher handles queries separately.

The default in-memory dispatchers are registered automatically by AddChatterCqrs (and are also available via AddInMemoryMessageDispatchers() / AddInMemoryQueryDispatcher()).

Command Pipeline

Commands can be wrapped in an ordered chain of cross-cutting behaviors — the equivalent of middleware for command handling (e.g. logging, validation, transactions). A behavior implements ICommandBehavior<TMessage>:

using Chatter.CQRS.Commands;
using Chatter.CQRS.Context;
using Chatter.CQRS.Pipeline;
using System.Threading.Tasks;

public class LoggingBehavior<TMessage> : ICommandBehavior<TMessage> where TMessage : ICommand
{
    public async Task Handle(TMessage message, IMessageHandlerContext context, CommandHandlerDelegate next)
    {
        // before the handler / next behavior
        await next();
        // after
    }
}

next is a CommandHandlerDelegate that invokes the next behavior in the chain, ending with the actual command handler. Behaviors execute in registration order (the pipeline composes them so the first-registered behavior is the outermost).

Add behaviors when registering, via the CommandPipelineBuilder:

services.AddChatterCqrs(
    configuration,
    pipelineBuilder: pipeline =>
    {
        // open-generic behavior applied to ALL commands
        pipeline.WithBehavior(typeof(LoggingBehavior<>));
        // closed-generic behavior scoped to one command
        pipeline.WithBehavior(typeof(ValidateCreateOrderBehavior));
    },
    messageHandlerSourceBuilder: source => source.WithMarkerTypes(typeof(CreateOrderHandler)));

Under the hood the pipeline is ICommandBehaviorPipeline<TMessage> (default implementation CommandBehaviorPipeline<TMessage>). When a command is dispatched, CommandDispatcher runs the pipeline if one exists; otherwise it invokes the handler directly.

You can also register behaviors directly on the IServiceCollection:

services.AddPipelineBehavior(typeof(LoggingBehavior<>)); // open generic → all commands
services.AddPipelineBehavior(typeof(ValidateCreateOrderBehavior)); // closed generic → one command

Diagnostics (optional, opt-in)

Command and Event dispatch are instrumented with OpenTelemetry-compatible tracing and metrics. The instrumentation is off until an application opts in, and Chatter.CQRS takes no dependency on any OpenTelemetry.* NuGet package — it is built on the .NET base class library only: System.Diagnostics.ActivitySource for spans and System.Diagnostics.Metrics.Meter for instruments.

Turning it on

The ActivitySource and the Meter are both named after the emitting assembly — Chatter.CQRS. Subscribe on your own OpenTelemetry provider with a prefix wildcard, or name the scopes exactly:

services.AddOpenTelemetry()
        .WithTracing(t => t.AddSource("Chatter.*"))    // or .AddSource("Chatter.CQRS")
        .WithMetrics(m => m.AddMeter("Chatter.*"));    // or .AddMeter("Chatter.CQRS")

Chatter.MessageBrokers emits under its own separate scope, also named after its assembly, so the two modules can be sampled and filtered independently. The "Chatter.*" form above subscribes to both.

Any .NET ActivityListener / MeterListener works just as well — an OpenTelemetry provider merely subscribes to these base-class-library primitives, it is not a prerequisite for them.

What is emitted

Every row below states when its signal is emitted: a blank condition cell is a defect, and Always is a positive claim that the emit site is unconditional, not a default. One row per facet — no comma-joined lists.

Spans. At most one span per Command dispatch and per Event dispatch.

Span Name Kind Started by Started when
dispatch dispatch followed by the short name of the compile-time TMessage type argument, not the runtime type — a variable declared SubmitOrder gives dispatch SubmitOrder, a variable declared ICommand gives dispatch ICommand ActivityKind.Internal CommandDispatcher.Dispatch<TMessage> and EventDispatcher.Dispatch<TMessage> A .NET ActivityListener is attached to the Chatter.CQRS source and samples this dispatch; when it is not, no span exists and only the metric below can be recorded
Attribute Span Value Emitted Name origin
chatter.message.type dispatch The fully qualified name of the compile-time TMessage type argument, not the runtime type — a variable declared SubmitOrder gives Acme.Ordering.SubmitOrder (span name dispatch SubmitOrder), a variable declared ICommand gives Chatter.CQRS.Commands.ICommand (span name dispatch ICommand) Always — set unconditionally on every started span Chatter-native
chatter.dispatch.kind dispatch command on the Command dispatch path, event on the Event dispatch path Always — set unconditionally on every started span Chatter-native
error.type dispatch The fully qualified exception type name Failure only — when the dispatch threw OpenTelemetry semantic convention
Status — the span's own status field, not a tag dispatch Error, with the exception's message as the status description Failure only — when the dispatch threw Activity.SetStatus, .NET base class library

The exception event carries the same name on both target frameworks, but Chatter populates its attributes on net8.0 only; on net10.0 the .NET base class library writes them.

Event Span Attributes Emitted
exception dispatch exception.type — on net8.0 Chatter writes the fully qualified exception type name; on net10.0 the value is whatever Activity.AddException writes Failure only, and only when the .NET ActivityListener requested all data (Activity.IsAllDataRequested)
exception dispatch exception.message — on net8.0 Chatter writes Exception.Message; on net10.0 the value is whatever Activity.AddException writes Failure only, and only when the .NET ActivityListener requested all data (Activity.IsAllDataRequested)
exception dispatch exception.stacktrace — on net8.0 Chatter writes Exception.ToString(), which carries the type, message and stack trace; on net10.0 the value is whatever Activity.AddException writes Failure only, and only when the .NET ActivityListener requested all data (Activity.IsAllDataRequested)

Metrics.

Instrument Type Unit Advised buckets Records Recorded when
chatter.cqrs.dispatch.duration Histogram<double> s (seconds) 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10 — published as instrument advice on net10.0 only; on net8.0 the instrument carries none. See Histogram bucket boundaries below. Elapsed time of one Command or Event dispatch, measured from before the span is started until the handler — or, for an Event, the last handler — returns or throws Once per dispatch, on success and on failure alike, and only while the instrument itself is enabled on a .NET MeterListener; a dispatch that ran with diagnostics off records nothing
Attribute Instruments Value Emitted
chatter.message.type chatter.cqrs.dispatch.duration The fully qualified name of the compile-time TMessage type argument — the same value the span attribute above carries Always
chatter.dispatch.kind chatter.cqrs.dispatch.duration command on the Command dispatch path, event on the Event dispatch path Always
error.type chatter.cqrs.dispatch.duration The fully qualified exception type name, resolved by the same code that sets the span's error.type, so the two signals cannot disagree Failure only — when the dispatch threw

Query dispatch is not instrumented.

Histogram bucket boundaries

chatter.cqrs.dispatch.duration records seconds. The OpenTelemetry .NET SDK's default explicit histogram boundaries are millisecond-sized (0, 5, 10, 25, ... 10000), so a collector that applies them puts every realistic measurement in the first bucket and P50, P90 and P99 all report the same number forever. Chatter.CQRS therefore publishes seconds-sized bucket boundaries on the instrument itself. The boundary set is the one the OpenTelemetry messaging semantic conventions specify for duration histograms — borrowed for its shape, since no semantic convention covers in-process CQRS dispatch itself — and is listed in the Metrics table above.

They are advice, not a setting. The boundaries are published as instrument advice — a default that an application's own view overrides. An application that already registers a view for chatter.cqrs.dispatch.duration keeps winning exactly as it did before; nothing it configured changes. Advice is the right layer for this precisely because it cannot take that choice away from the application.

Advice is published on net10.0 only. The base class library type that carries instrument advice does not exist in the net8.0 shared framework, and this package takes no package dependency to reach it. On net8.0 the instrument therefore ships with no advice at all, and the collector falls back to its own millisecond-sized defaults.

On net8.0, configure the equivalent view in your own application. AddView and ExplicitBucketHistogramConfiguration are OpenTelemetry.Metrics types that come from your application's OpenTelemetry packages — this package still takes no dependency on any OpenTelemetry.* NuGet package, and the snippet below adds none to it:

using OpenTelemetry.Metrics;

services.AddOpenTelemetry()
        .WithMetrics(m => m
            .AddMeter("Chatter.CQRS")
            .AddView("chatter.cqrs.dispatch.duration", new ExplicitBucketHistogramConfiguration
            {
                Boundaries = new double[] { 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10 }
            }));

The same view is harmless on net10.0: it overrides advice that already carries these boundaries. This net8.0 caveat retires when net8.0 is dropped and the package single-targets net10.0 after .NET 8 reaches end of life on 2026-11-10 — tracked in issue #395.

Off means off

When nothing subscribes to the Chatter.CQRS source or meter, nothing is emitted and no work is done. Every entry point checks whether Chatter's own source has a subscriber as its first statement and returns before a span name, a tag collection, or a timestamp is constructed, and dispatch keeps its existing shape — no async state machine and no extra allocation is introduced on the un-instrumented path. The guarantee is per-dispatch: constructing the ActivitySource and Meter themselves is a one-time static initialization per process, which is unavoidable for any ActivitySource-based design.

The guard is Chatter's own subscriber check — never Activity.Current, which is non-null in any host running unrelated instrumentation and therefore does not mean Chatter diagnostics are on.

Attribute names are data, not API

Attributes prefixed chatter. are Chatter-native: no OpenTelemetry semantic convention covers in-process CQRS dispatch. The remaining names (error.type, exception.*) are OpenTelemetry semantic conventions pinned to v1.30.0. Because telemetry attributes are emitted data rather than a compile-time type surface, they may change in a minor release when that pin advances. Dashboards and alert queries that hard-code attribute names should expect to be revisited on a pin bump; the bump is announced in this package's CHANGELOG.

Design rationale and the off-guard rules are recorded in ADR-0010.

Domain Language

Terms such as Command, Query, Read Model, Event (Domain vs Integration), Aggregate, Command Pipeline, Message Context, and Dispatcher follow the project's ubiquitous language. See ../CONTEXT.md for the full glossary and relationships.

← All Chatter modules

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 Chatter.CQRS:

Package Downloads
Chatter.MessageBrokers

A message broker adapter library built on top of Chatter.CQRS.

Chatter.IntegrationEventRelay

Capture domain events from changes in a SQL database and relay them to message broker infrastructure as integration events. Add a change source package, such as Chatter.IntegrationEventRelay.ServiceBroker.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.21.0 1,830 9/26/2026
0.20.0 116 9/26/2026
0.19.0 1,454 9/24/2026
0.18.0 170 9/24/2026
0.17.0 313 9/23/2026
0.16.0 491 9/13/2026
0.15.2 307 9/11/2026
0.15.1 126 9/11/2026
0.15.0 117 9/11/2026
0.12.0 241 9/11/2026
0.11.1 686 9/2/2026
0.11.0 276 9/1/2026
0.10.0 413 8/31/2026
0.9.0 169 8/30/2026
0.8.1 3,828 6/16/2026
0.8.0 563 5/30/2026
0.7.0 35,706 3/3/2023
0.6.2 13,034 12/30/2021
0.6.1 547 12/16/2021
0.6.0 9,080 11/11/2021
Loading failed