Skip to content

CQRS in C# and .NET with Cratis Arc

CQRS (Command Query Responsibility Segregation) separates operations that change state, called commands, from queries that read it. Each has its own model, so a command can accept the inputs needed for a decision while a query returns what a screen needs. That separation does not require separate databases or event sourcing.

Cratis Arc implements this pattern for ASP.NET Core. A command is a C# record with a Handle() method, and a query is a static method on a read model. Arc exposes them over HTTP and generates typed TypeScript clients, called proxies, for the frontend. Cratis Chronicle is optional; add it when you want to store the write side as events.

The examples below follow author registration from a database write to an event-backed version. If you are still deciding whether the separation is useful for your application, CQRS explained covers the design trade-offs.

Capability How it looks in Arc Publication
Commands [Command] record with Handle(); endpoint generated Packages published
Queries and read models [ReadModel] record with static query methods Packages published
Live queries A query returning ISubject<T> streams changes to the client Packages published
Validation Data annotations or FluentValidation CommandValidator<T>, run before Handle() Packages published
Authorization [Roles] and [Authorize] on commands and query methods Packages published
Typed frontend TypeScript proxies generated from the same types Packages published
Event sourcing Chronicle: Handle() returns an event; a projection fills the read model; optional Packages published

The packages listed above are published. The capability matrix shows each row per language, checked against source and tests. Arc runs on ASP.NET Core and on a lighter standalone Arc.Core host; the integrations for MongoDB and Entity Framework Core are separate packages.

A library application needs to register authors and list them. RegisterAuthor carries the new author’s identifier and name; Handle() writes the document to MongoDB. There is no event log in this version:

using Cratis.Arc.Commands.ModelBound;
using MongoDB.Driver;
[Command]
public record RegisterAuthor(Guid Id, string Name)
{
public Task Handle(IMongoCollection<Author> authors) =>
authors.InsertOneAsync(new Author(Id, Name));
}

The query side is a read model with a static method. Arc resolves IMongoCollection<Author> from the container, serves the method over HTTP, and generates a proxy for the frontend:

using Cratis.Arc.Queries.ModelBound;
using MongoDB.Driver;
[ReadModel]
public record Author(Guid Id, string Name)
{
public static IEnumerable<Author> AllAuthors(IMongoCollection<Author> authors) =>
authors.Find(_ => true).ToList();
}

The collection connects these two operations: the command inserts an author, and AllAuthors reads the stored authors as a snapshot. Neither type needs a controller or a route attribute. Arc discovers the operations and supplies the collection through dependency injection, but you still configure the host and MongoDB connection. Follow Arc’s .NET getting started guide for that runnable setup.

Validation, authorization and live queries

Section titled “Validation, authorization and live queries”

Validation and authorization sit at the boundary, so Handle() stays about behavior. Annotate the record’s properties and Arc rejects bad input before Handle() runs. This example is from the validation guide:

[Command]
public record AllocateLabeledIdentifier(
[property: Required] string Label,
[property: Range(1, 100)] int Copies)
{
public Guid Handle() => Guid.NewGuid();
}

Put [Roles(...)] on a command or on a query method and Arc checks the caller’s roles first. Authorization applies when the call goes through Arc’s pipelines; calling Handle() directly from C# bypasses it. See authorizing commands and queries.

For a live read model, return ISubject<T>. The client receives the current result and then each change, and the generated React proxy exposes it as a hook:

[ReadModel]
public record Author([property: Key] AuthorId Id, AuthorName Name)
{
[Roles(nameof(UserRole.Librarian))]
public static ISubject<IEnumerable<Author>> AllAuthors(IMongoCollection<Author> collection) =>
collection.Observe();
}
const [authors] = AllAuthors.use();

To keep the registration history, change what the command produces. Instead of inserting the author directly, Handle() returns AuthorRegistered, a fact that Arc appends to Chronicle. The query can keep its shape if the projection writes to the collection it already reads:

using Cratis.Arc.Commands.ModelBound;
using Cratis.Chronicle.Events;
[Command]
public record RegisterAuthor(EventSourceId Id, string Name)
{
public AuthorRegistered Handle() => new(Name);
}
[EventType]
public record AuthorRegistered(string Name);

A projection then fills the read model. With [FromEvent<AuthorRegistered>], Chronicle maps the event’s Name onto the read model by convention, and the query keeps its signature:

[ReadModel]
[FromEvent<AuthorRegistered>]
public record Author(AuthorId Id, AuthorName Name)
{
public static ISubject<IEnumerable<Author>> AllAuthors(IMongoCollection<Author> collection) =>
collection.Observe();
}

The generated proxies and React screens do not change. Moving an existing slice needs more than these type changes: a running Chronicle server, a sink that matches the collection the query reads, and a plan for existing rows. The add event sourcing guide covers each. In an application that uses both products, the Cratis package wires Arc and Chronicle with AddCratis and UseCratis.

Chronicle also provides reducers, reactors and projections for the read side. Projections and read models explains the choice between them. For the storage side, see event sourcing in .NET.

Use it when reads and writes have different shapes, load or rules; when the frontend needs typed, live data; or when you expect to add event sourcing later and want the contract between commands and queries to stay stable.

For a single form over a single table, plain CRUD may be enough. CQRS adds types to maintain: a command, a read model and often a validator per behavior. Separate commands and queries do not themselves make reads asynchronous, but Chronicle projections do introduce a processing delay. A screen that queries immediately after a write must account for that. CQRS explained discusses the trade-offs in more depth.

Arc is not a mediator library. It owns hosting, endpoints and proxies as well as dispatch. If you only want in-process command handlers behind your own controllers, a smaller library fits better. Coming from MediatR and MVC maps the two.

It depends on how much you want a framework to own. You can write handlers by hand or use a mediator library. Arc is the option where commands, queries, validation, authorization and frontend proxies share one model. Try its getting started guide and compare against what you have.

No. CQRS is a design choice, not a library. Arc dispatches commands and queries itself and exposes them over generated HTTP endpoints.

Can I use CQRS without event sourcing in .NET?

Section titled “Can I use CQRS without event sourcing in .NET?”

Yes. Arc works with MongoDB or Entity Framework Core and has no Chronicle dependency. See CQRS without event sourcing.

How does the frontend call commands and queries?

Section titled “How does the frontend call commands and queries?”

Arc generates typed TypeScript proxies from your C# commands and queries after the build. React components call them as typed methods and hooks. See understanding the proxy boundary.

Does Arc work with languages other than C#?

Section titled “Does Arc work with languages other than C#?”

Yes. See CQRS in Kotlin and Java, CQRS in TypeScript and Node.js and CQRS in Elixir. They do not have full parity with .NET.