Skip to content

Seed a Cratis Chronicle event store with C#

To seed a Cratis Chronicle event store in C#, implement ICanSeedEvents and define the initial events your application needs. The .NET client discovers your seeder and registers its events when it connects, giving a new environment a starting history without a separate append script.

Start with a running kernel and a connected .NET client. Choose the scope before defining seeds: global seeds reach every namespace in the event store, including tenants created later. A namespace is a separate data scope within an event store. Use ForNamespace(...) for development or sample data that belongs only in a named namespace.

Define the facts you want in the starting history. These examples use C# records marked with [EventType], so Chronicle can discover and register their event types:

using Cratis.Chronicle.Events;
[EventType]
public record EvtSeedingUserRegistered(string Email, string DisplayName);
[EventType]
public record EvtSeedingEmailVerified(string Email);
[EventType]
public record EvtSeedingProfileUpdated(string DisplayName);
[EventType]
public record EvtSeedingOrderPlaced(string UserId, decimal Amount);

View C# snippet source on GitHub

Implement ICanSeedEvents. Chronicle calls its Seed method with an IEventSeedingBuilder; use that builder to associate events with an event source identifier, the key for the entity whose history they belong to:

using Cratis.Chronicle.Seeding;
public sealed class EvtSeedingUserSeeding : ICanSeedEvents
{
public void Seed(IEventSeedingBuilder builder)
{
builder
.For<EvtSeedingUserRegistered>("user-123", [
new("john@example.com", "John")
])
.ForEventSource("user-456", [
new EvtSeedingUserRegistered("jane@example.com", "Jane"),
new EvtSeedingEmailVerified("jane@example.com")
]);
}
}

View C# snippet source on GitHub

Here, For<TEvent> adds events of one type for user-123. ForEventSource adds the registration and verification events for user-456 in the order shown. Both calls use the top-level builder, so these are global seeds. Use the namespace-scoped builder shown below if these users should exist only in a development namespace.

Pass a list to For<TEvent> when one event source needs several events of that type:

using Cratis.Chronicle.Seeding;
public sealed class EvtSeedingMultipleSameTypeSeeding : ICanSeedEvents
{
public void Seed(IEventSeedingBuilder builder)
{
builder.For<EvtSeedingUserRegistered>("user-123", [
new("john@example.com", "John"),
new("jane@example.com", "Jane")
]);
}
}

View C# snippet source on GitHub

Both entries belong to user-123; changing the email in the payload does not create a different event source. Use separate source identifiers if the entries represent different users.

Use ForEventSource when the starting history contains different event types for the same source:

using Cratis.Chronicle.Seeding;
public sealed class EvtSeedingMixedTypesSeeding : ICanSeedEvents
{
public void Seed(IEventSeedingBuilder builder)
{
builder.ForEventSource("user-123", [
new EvtSeedingUserRegistered("john@example.com", "John"),
new EvtSeedingEmailVerified("john@example.com"),
new EvtSeedingProfileUpdated("John Doe")
]);
}
}

View C# snippet source on GitHub

The registration, verification, and profile update form the initial history of user-123. Rerunning these same definitions skips occurrences already seeded successfully.

Pass an event stream type and identifier to For or ForEventSource to route seeds onto a specific stream. The optional event source type defaults to Default. These overloads also work on the builder returned by ForNamespace.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Seeding;
public sealed class EvtStreamRoutedSeeder : ICanSeedEvents
{
public void Seed(IEventSeedingBuilder builder)
{
builder.For("company-123", "Offices", "office-1", [
new EvtStreamRoutedOfficeOpened("Oslo")
], "Company");
builder.ForNamespace("tenant-a").ForEventSource(
"company-123", "Offices", "office-2", [
new EvtStreamRoutedOfficeOpened("Bergen")
], "Company");
}
}
[EventType]
public record EvtStreamRoutedOfficeOpened(string City);

View C# snippet source on GitHub

The first call seeds the Offices stream office-1 under company-123 across namespaces. The second targets only tenant-a, using the same source but stream identifier office-2. Both record Company as the event source type.

Use ForEvents when individual entries need different routes. Its EventForEventSourceId entries can specify an EventSource definition type and an EventStream name; Chronicle resolves their routing from the discovered definition and rejects contradictory explicit types. Entry tags are combined with static event-type tags. Set EventSource whenever you use a typed EventStream: without EventSource, the stream name is ignored and only the explicit EventStreamType and EventStreamId determine stream routing. ForEvents uses the wrapper’s routing and tags, not its append-specific occurred time, subject, causation or structured named tags.

Routing is part of seed identity: identical payloads on different streams are separate seed entries. Omitting routing preserves the defaults used by previously stored seed definitions, so adopting this API does not append legacy seeds again.

Non-default routing requires a kernel that confirms seeding routing support. Against an older kernel, Register() throws EventSeedingRoutingNotSupported before sending any seed entries, including unrouted entries in the same buffer. Upgrade the kernel before retrying that buffer. A buffer containing only default routing still registers against older kernels.

Decide whether a build or environment should offer sample data before you register it. The example uses conditional compilation, so the seeder exists only in builds that define DEBUG:

using Cratis.Chronicle;
using Cratis.Chronicle.Seeding;
#if DEBUG
public sealed class EvtSeedingDevelopmentSeeding : ICanSeedEvents
{
public void Seed(IEventSeedingBuilder builder)
{
builder.ForNamespace(EventStoreNamespaceName.Default).For<EvtSeedingUserRegistered>("dev-user-1", [
new("dev@example.com", "Dev User")
]);
}
}
#endif

View C# snippet source on GitHub

Chronicle does not distinguish between development and production seed data. Use your build configuration or runtime settings to control when the seeder runs, and ForNamespace(EventStoreNamespaceName.Default) to keep its entries out of other namespaces. Neither choice removes events already appended.

With a .NET client and kernel that support global declarations, startup replaces the program’s stored global declaration even when its new global set is empty. The cleanup procedure below covers seeds previously registered globally.

Keep seed definitions beside the feature they support. Separate ICanSeedEvents implementations let you change the user and order starting histories independently:

using Cratis.Chronicle.Seeding;
public sealed class EvtSeedingUserFeatureSeeding : ICanSeedEvents
{
public void Seed(IEventSeedingBuilder builder)
{
builder.For<EvtSeedingUserRegistered>("test-user-1", [
new("test1@example.com", "Test User 1")
]);
}
}
public sealed class EvtSeedingOrderFeatureSeeding : ICanSeedEvents
{
public void Seed(IEventSeedingBuilder builder)
{
builder.For<EvtSeedingOrderPlaced>("test-order-1", [
new("test-user-1", 100.00m)
]);
}
}

View C# snippet source on GitHub

For and ForEventSource on the top-level builder define global seeds. The server stores them per event store and applies them to every existing namespace and each namespace created later.

Opening a store for a new namespace creates that namespace. The kernel applies stored global seeds asynchronously; there is no guarantee they arrive before your application’s first write. Do not rely on that timing for startup logic.

Use ForNamespace to get a builder that targets only one namespace. In this example, the product is global, while tenant-specific users and organization events stay in their named namespaces:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Seeding;
[EventType]
public record EvtSeedingProductCreated(string Name, decimal Price);
[EventType]
public record EvtSeedingOrganizationCreated(string Name);
[EventType]
public record EvtSeedingBillingSetUp(string BillingEmail);
public sealed class EvtSeedingTenantSeeding : ICanSeedEvents
{
public void Seed(IEventSeedingBuilder builder)
{
// Global seed data — applied to every namespace
builder.For<EvtSeedingProductCreated>("product-1", [
new("Laptop", 1299.00m)
]);
// Namespace-scoped seed data — applied only to the "acme" namespace
builder.ForNamespace("acme")
.For<EvtSeedingUserRegistered>("user-1", [
new("admin@acme.com", "Acme Admin")
]);
// A second namespace with different seed data
builder.ForNamespace("contoso")
.For<EvtSeedingUserRegistered>("user-1", [
new("admin@contoso.com", "Contoso Admin")
])
.ForEventSource("org-1", [
new EvtSeedingOrganizationCreated("Contoso"),
new EvtSeedingBillingSetUp("contoso@billing.com")
]);
}
}

View C# snippet source on GitHub

The scoped builder supports the same For<TEvent> and ForEventSource methods as the global builder. Each namespace receives only its own scoped events in addition to any global events. ForNamespace(EventStoreNamespaceName.Default) never sends those entries to another namespace.

An authoritative global seed set is the complete set of global seeds a program currently declares through its discovered seeders. Each declaration replaces that program’s previous one, including when the new set is empty. Removing an entry from ICanSeedEvents stops it reaching namespaces created afterwards. Events already appended to existing namespaces are never retracted.

Explicitly queued globals work differently. Entries added through eventStore.Seeding.For(...) or an independent CreateEventSeeding() buffer remain append-only. A later declaration does not remove them, even if an identical seed was already declared. Use discovered seeders when future namespaces should follow your current definitions, and explicit additions when the entries should remain part of the stored global set.

Programs sharing a store can declare the same seed without multiplying it. A namespace receives the largest occurrence count from any program’s declaration or explicit additions, not the sum across programs. For example, if one program declares an entry twice and another declares it once, the namespace receives two occurrences. Seed identity includes the event source, event type, content, tags, and routing.

Clearing one program’s declaration leaves a seed in place if another program still declares it or has added it explicitly. Existing namespaces receive only missing occurrences; reducing a count never retracts events.

If a discovered seeder cannot be activated or its Seed method fails, the client logs the failing seeder types and keeps the previous global declaration. It sends no discovered global declaration during that registration and does not store the partial discovered set as explicit additions. Namespace-scoped and manually queued entries still register. The next registration retries discovery; a complete successful discovery then declares the global set.

Ownership uses ChronicleOptions.ProgramIdentifier, falling back to the entry assembly name when the option is still "[N/A]". Set a distinct, stable ProgramIdentifier for each program sharing a store, so one program does not replace another’s declaration.

Both the .NET client and kernel must support declarations for replacement to take effect. Older clients keep append-only behavior. A newer client can still register default-routed seeds against an older kernel, but that kernel ignores declarations and retains its stored globals. The first authoritative registration after upgrading also clears legacy stored global seeds whose owner was not recorded. Other programs’ owned declarations and explicit additions remain stored.

  1. Upgrade both the .NET client and the kernel.
  2. Remove the development seeder, or scope its entries with ForNamespace(EventStoreNamespaceName.Default).
  3. Start the application once so it declares its remaining global set, even if empty.

New namespaces no longer receive the removed declarations or legacy global entries. Existing namespaces keep all events already appended. This does not remove explicitly queued globals.

Register corrected seed definitions without reconnecting

Section titled “Register corrected seed definitions without reconnecting”

A command or transport error leaves the attempted entries in the event store’s default Seeding buffer. You can retry the same entries after a transient failure without duplicating successful occurrences.

If the definitions themselves were wrong, create an independent empty buffer so the corrected set is not combined with retained entries:

using Cratis.Chronicle;
using Cratis.Chronicle.Seeding;
public static class EvtSeedingCorrection
{
public static async Task Register(IEventStore eventStore)
{
var correctedSeeding = eventStore.CreateEventSeeding();
correctedSeeding.For<EvtSeedingUserRegistered>("user-123", [
new("john@example.com", "John Doe")
]);
await correctedSeeding.Register();
}
}

View C# snippet source on GitHub

The new buffer uses the event store’s existing connection, event types, serializer, and client configuration. A failure from its Register() call still propagates normally.

With automatic discovery enabled, the .NET client discovers seeders at application startup. It sends the discovered global set once per event store name per connection lifetime, even if it opens stores for several namespaces. Reconnecting sends that global set again. Each namespace store still sends its ForNamespace(...) entries during registration.

Chronicle tracks successful occurrences in each namespace, so restarting skips events already appended. If your seeder yields the same entry twice, both occurrences are appended. That remains true when the event type, source, and payload are identical; rerunning the list skips those two successful occurrences.

Events are appended in batches of 100. A batch is validated as a whole before anything is written, so one constraint violation prevents every entry in that batch from being appended. The server logs the rejection at Error with the violated constraint names and counts, and leaves those entries unseeded.

A rejected batch does not fail registration and is not reported to the client. Check the server log even when registration returns successfully. The client clears its buffer after that return, so correcting the definitions alone does not offer them again: restart the process or use CreateEventSeeding() to register the corrected set. Retrying the retained buffer applies only to command or transport errors, not to a server-side batch rejection.

Keep the starting history small and deterministic, with source identifiers you can recognize in the log. Group seeders by feature or scenario so changes remain easy to trace. For tenant-specific or environment-specific data, choose ForNamespace and control whether the seeder runs through build flags or runtime settings.

After starting the application, open Chronicle Workbench, select the intended event store and namespace, and inspect the event log for the source identifiers in your seeder. For the first example, look for the registration event under user-123 and the registration and verification events under user-456. Check the server log for rejected batches if events are missing. Restart with unchanged definitions and confirm those successful occurrences are not appended again.