Skip to content

Add Chronicle to a worker service

A worker service is the natural home for the reacting side of an event-sourced system: no web front end, just a long-running host that processes events, runs scheduled jobs, or keeps derived data up to date. Setup is mostly a matter of letting the generic host’s DI container do the wiring — register Chronicle once, then inject what you need wherever you need it.

We’ll build the same small library domain as the other host guides. If you’re building a web API instead, the ASP.NET Core guide covers that host; for the bare-bones, no-container version, see the console guide.

Have the Chronicle kernel running locally. Run Chronicle locally brings it up with a single docker run and lists the prerequisites (.NET 8+, Docker); this guide assumes it’s listening on chronicle://localhost:35000.

Create a folder for your project, then a .NET worker service inside it:

Terminal window
dotnet new worker

Add a reference to the Chronicle client package:

Terminal window
dotnet add package Cratis.Chronicle

The generic host builds your app through IHostApplicationBuilder, which already has a dependency-injection container. One call hooks Chronicle into it and names the event store to use:

using Microsoft.Extensions.Hosting;
public static class GetStartedWorkerRegistration
{
public static async Task ConfigureAndRun(string[] args)
{
var builder = Host.CreateApplicationBuilder(args);
builder.AddCratisChronicle(options => options.EventStore = "Quickstart");
builder.Services.AddHostedService<GetStartedWorker>();
var host = builder.Build();
await host.RunAsync();
}
}

View C# snippet source on GitHub

Like the ASP.NET Core host, AddCratisChronicle registers Chronicle’s services — IEventStore, IEventLog, IReactors, IReducers, IProjections — and automatically discovers and registers your artifacts (reactors, reducers, projections) from the loaded assemblies. It reads its connection settings from the Cratis:Chronicle section of appsettings.json:

AddCratisChronicle

Host.CreateApplicationBuilder

DI container (auto-discovers artifacts)

IEventStore · IEventLog · IReactors · IReducers · IProjections

your BackgroundService

appsettings.json
{
"Cratis": {
"Chronicle": {
"ConnectionString": "chronicle://localhost:35000",
"EventStore": "Quickstart"
}
}
}

Everything in Chronicle starts with a fact. You model facts as record types marked with [EventType] — records because an event, once it happened, never changes. The attribute is how Chronicle discovers the type; it takes no name, the type name is the identity.

Here are the facts of a small library — a book arrives, gets borrowed, and comes back:

using Cratis.Chronicle.Events;
[EventType]
public record GetStartedBookAdded(string Title, string Isbn);
[EventType]
public record GetStartedBookBorrowed(string MemberName);
[EventType]
public record GetStartedBookReturned;

View C# snippet source on GitHub

BookReturned carries no data at all — that it happened, on a particular book’s stream, is the whole story. Not every fact needs a payload.

You record a fact by appending it to an event sequence. Chronicle gives you one by default — the event log, the main sequence you’ll use, much like the main branch of a Git repository. Reach it through the event store:

using Cratis.Chronicle;
public class GetStartedBookService(IEventStore eventStore)
{
public async Task<Guid> AddBook()
{
var eventLog = eventStore.EventLog;
var bookId = Guid.NewGuid();
await eventLog.Append(bookId, new GetStartedBookAdded("The Pragmatic Programmer", "978-0135957059"));
return bookId;
}
}

View C# snippet source on GitHub

That first argument is the event source id — the identity of the thing this fact is about, like a primary key. Every event you append against bookId becomes part of that book’s stream of history.

Run your app, then open the workbench, pick your event store, and select Sequences — your GetStartedBookAdded is sitting there, permanent and in order. In a fresh event store the first event is at sequence number 0.

Chronicle Workbench showing events

Events are the write side — the source of truth. To read current state you don’t query the log directly; you let Chronicle fold the events into a read model for you. The declarative way to do that is a projection: you declare the shape you want and which events feed each field, and Chronicle keeps it in sync — no update code, ever.

using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[FromEvent<GetStartedBookAdded>]
public record GetStartedBook(
[Key]
Guid Id,
string Title,
string Isbn,
[SetValue<GetStartedBookAdded>(false)]
[SetValue<GetStartedBookBorrowed>(true)]
[SetValue<GetStartedBookReturned>(false)]
bool OnLoan,
[SetFrom<GetStartedBookBorrowed>(nameof(GetStartedBookBorrowed.MemberName))]
string? BorrowedBy);

View C# snippet source on GitHub

Read the attributes as a sentence: a book comes into the view from BookAdded; OnLoan is false when it’s added, true when borrowed, false again when returned; BorrowedBy is whoever borrowed it. You’re declaring how facts map onto the view — Chronicle replays the events in order and applies the mapping.

One view rarely answers every question. The librarian’s next one is “what’s out on loan right now?” — and rather than filtering GetStartedBook, you declare a second, purpose-built read model whose very existence tracks the loan:

using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[FromEvent<GetStartedBookBorrowed>]
[RemovedWith<GetStartedBookReturned>]
public record GetStartedBorrowedBook(
[Key]
Guid Id,
string MemberName);

View C# snippet source on GitHub

The moment a GetStartedBookBorrowed lands, a GetStartedBorrowedBook instance appears — keyed by the book’s id, its MemberName mapped by the same naming convention. When the matching GetStartedBookReturned arrives, [RemovedWith<GetStartedBookReturned>] removes the instance from the view again. The collection always holds exactly the books that are out right now — no flag to maintain, no filter to remember, no cleanup job. Kotlin and Java don’t currently have an equivalent to [RemovedWith<T>].

The most direct way to look at a read model is to ask Chronicle itself. IReadModels — reached through eventStore.ReadModels — hands you every instance of a read model, one call per view:

using Cratis.Chronicle;
public class GetStartedBookQueryService(IEventStore eventStore)
{
public async Task<(IEnumerable<GetStartedBook> Books, IEnumerable<GetStartedBorrowedBook> BorrowedBooks)> QueryBooks()
{
var books = await eventStore.ReadModels.GetInstances<GetStartedBook>();
var borrowedBooks = await eventStore.ReadModels.GetInstances<GetStartedBorrowedBook>();
return (books, borrowedBooks);
}
}

View C# snippet source on GitHub

These instances come from the sink. By default Chronicle materializes every projection into the sink storage configured for the event store — MongoDB unless you change it. For the default namespace the database is named after the event store (Quickstart), and each collection after its read model, pluralized: GetStartedBooks and GetStartedBorrowedBooks. That makes a query cheap — a database fetch, whatever the length of the history.

Materialization happens in the background as events arrive, so these reads are eventually consistent. An append completes when the event is in the log, not when the read model has caught up, so a query issued straight after an append can miss it. That is most noticeable on the first event against a fresh event store: processing that event also creates the projection pipeline and its storage for the first time, so the read straight after that append is the one most likely to come back empty. Query again a moment later and the book is there.

When a read has to include the event you just appended, you have two tools. Mark the read model passive, and Chronicle keeps it out of the sink and computes it from its events on every read. Or keep it materialized and wait for the append’s observers to catch up before reading. Read model consistency compares the two.

Getting a collection of instances covers the details, including the event count you can pass to replay a read model from the beginning instead. Kotlin and Java currently only support fetching a single instance by key (getInstanceByKey) — fetching every instance of a read model isn’t available yet.

GetInstances returns every stored instance at once. The Materialized API reads the same stored instances back a page at a time. Kotlin and Java don’t currently have a materialized/paging query API at all; Elixir’s equivalent pages by page number rather than skip/take:

using Cratis.Chronicle;
public class GetStartedBookPagingService(IEventStore eventStore)
{
public async Task<IEnumerable<GetStartedBook>> GetPage() =>
await eventStore.ReadModels.Materialized.GetInstances<GetStartedBook>(skip: 0, take: 20);
}

View C# snippet source on GitHub

skip and take are plain paging (they default to 0 and 50), so you can window through a large collection without ever loading all of it — Materialized read models shows the paging and observing patterns.

Neither call filters, though: GetInstances returns everything (you’d filter with LINQ in memory), and Materialized only pages. When you need to filter efficiently — “which books are on loan?” — query the sink’s database directly with its native tools. Our sink is MongoDB, so GetStartedBooks is an ordinary collection that your language’s MongoDB driver can query (the Chronicle client does not bring one in; add it to your project):

using MongoDB.Driver;
public class GetStartedBooks(IMongoCollection<GetStartedBook> collection)
{
public IEnumerable<GetStartedBook> OnLoan() => collection.Find(b => b.OnLoan).ToList();
}

View C# snippet source on GitHub

Append a GetStartedBookBorrowed against the same bookId, query again, and OnLoan is true with BorrowedBy set — and a GetStartedBorrowedBook now sits in its collection. Append a GetStartedBookReturned and both flip back: the flag clears, the GetStartedBorrowedBook disappears. You never wrote an UPDATE. The trade-offs between the on-demand and materialized paths are laid out in read model consistency.

Projections build state. When you need to do something the moment a fact lands — notify someone, call another system — you write a reactor. IReactor is a marker; you just add a method whose first parameter is the event you care about, and Chronicle routes matching events to it:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reactors;
public class GetStartedBookReturnedNotifier : IReactor
{
public Task Returned(GetStartedBookReturned @event, EventContext context)
{
// context.EventSourceId is the BookId this happened to
Console.WriteLine($"Book {context.EventSourceId} was returned — notify the next member in line.");
return Task.CompletedTask;
}
}

View C# snippet source on GitHub

No registration, no wiring — drop the class in and every GetStartedBookReturned flows to it. Reactors must be idempotent, because the same event may be delivered more than once (during a replay or a recovery). Delivery identity explains what Chronicle does and does not guarantee there. In a real app you’d inject a notification service here — the tutorial and the Reactors guide show that, along with how reactors get their dependencies under a host.

That’s the whole loop — append → project → react. The tutorial builds exactly this library one concept at a time and explains each as you go; the Projections, Reducers, and Reactors guides go deeper on each piece.

In a worker you append from your BackgroundService rather than inline. Inject IEventStore (or IEventLog directly) and append inside ExecuteAsync:

using Cratis.Chronicle;
using Microsoft.Extensions.Hosting;
public class GetStartedWorker(IEventStore eventStore) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await eventStore.Connection.Connect();
var bookId = Guid.NewGuid();
await eventStore.EventLog.Append(bookId, new GetStartedBookAdded("The Pragmatic Programmer", "978-0135957059"));
// Keep running so reactors and projections keep processing.
await Task.Delay(Timeout.Infinite, stoppingToken);
}
}

View C# snippet source on GitHub

The projections and the GetStartedBookReturnedNotifier reactor pick those events up from the kernel — the worker stays alive to keep processing them.

The GetStartedBooks query reads documents Chronicle wrote, so the MongoDB driver needs to match how Chronicle stores them — register these conventions once at startup:

When you read Chronicle’s read models with the MongoDB driver, the driver has to expect the documents Chronicle writes. Three things matter:

  • Chronicle adds metadata fields of its own, such as __subject, so the driver must ignore elements your type does not declare.
  • Identifiers such as a Guid key are stored as standard UUIDs.
  • Element names match your property names exactly as declared, and each collection is named after its read model, pluralized. Chronicle only writes camel-case names if you opt into its camel case naming policy; match the driver to whichever policy you chose, or queries match nothing without reporting an error.
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Bson.Serialization.Serializers;
public static class GetStartedMongoDbDefaults
{
public static void Configure()
{
BsonSerializer
.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));
var pack = new ConventionPack
{
// Chronicle adds its own metadata fields to every document, such as __subject.
new IgnoreExtraElementsConvention(true)
// Element names match your C# property names by default. Add a
// CamelCaseElementNameConvention here only if you configured Chronicle
// with the camel case naming policy.
};
ConventionRegistry.Register("conventions", pack, t => true);
}
}

View C# snippet source on GitHub

Then register the database and the collection so a type can take an IMongoCollection<GetStartedBook> dependency:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MongoDB.Driver;
public static class GetStartedWorkerMongoRegistration
{
public static void ConfigureServices(IHostApplicationBuilder builder)
{
builder.Services.AddSingleton<IMongoClient>(new MongoClient("mongodb://localhost:27017"));
builder.Services.AddSingleton(provider => provider.GetRequiredService<IMongoClient>().GetDatabase("Quickstart"));
builder.Services.AddTransient(provider => provider.GetRequiredService<IMongoDatabase>().GetCollection<GetStartedBook>("GetStartedBooks"));
}
}

View C# snippet source on GitHub

Chronicle creates its discovered artifacts — reactors, reducers, projections — through the container. If an artifact is registered as a service, Chronicle uses that registration; otherwise it constructs the artifact itself and resolves its constructor parameters from the container. So you never have to register the reactor, but you do have to register what it depends on, such as the notification service a real waitlist reactor would take. As the solution grows, let Cratis Fundamentals register those services by convention:

using Cratis.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public static class GetStartedWorkerConventionRegistration
{
public static void ConfigureServices(IHostApplicationBuilder builder)
{
builder.Services
.AddBindingsByConvention()
.AddSelfBindings();
}
}

View C# snippet source on GitHub

AddBindingsByConvention registers any service that implements an interface of the same name prefixed with I (IFoo → Foo); AddSelfBindings registers concrete classes as themselves.

  • Multi-tenant namespaces — provide a custom IEventStoreNamespaceResolver to route operations per tenant. See Namespace resolution.
  • Structural dependencies — supply custom identity providers, correlation-id accessors, or namespace resolvers through the configure callback on AddCratisChronicle. See Structural dependencies.

You added Chronicle to a worker service with a single AddCratisChronicle call, pointed it at an event store through appsettings.json, and appended events from a BackgroundService — the generic host’s DI container discovered your reactors, reducers, and projections and handed you the services to use them. The same library domain runs here unchanged from the other hosts.

  • Build the domain step by step — the tutorial walks the library model one concept at a time.
  • Reacting to events — a worker’s main job; see Reactors for the patterns.
  • A different host — the same artifacts run unchanged behind a web API (ASP.NET Core) or with no container at all (console).