Skip to content

Declare Chronicle constraints with fluent rules

Declarative constraints keep an append-time rule in a dedicated class rather than on an event type. Use them when several events share one uniqueness rule, when a violation needs a dynamic message, or when you want to control the constraint’s name. In .NET, implement IConstraint and describe the rule through its fluent builder, chaining calls that select the events, properties, and release behavior.

For a rule that belongs directly on an event type or property, start with Model-bound constraints. Both approaches send definitions to the Chronicle Kernel, where the append is checked.

Rule you need Constraint
Reserve a value, such as a project name, so another event source cannot claim it Unique property
Allow an event only once per event source, or once per cycle ended by a release event Unique event type
Stop later appends in a selected scope after a closing event Closing stream

The following rule reserves a project’s name when it is created and releases the name when the project is removed. In .NET, put the declaration in Define:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Events.Constraints;
[EventType]
public record ConstraintsDeclarativeIndexProjectCreated(string Name);
[EventType]
public record ConstraintsDeclarativeIndexProjectRemoved;
public class ConstraintsDeclarativeIndexUniqueProjectName : IConstraint
{
public void Define(IConstraintBuilder builder) =>
builder.Unique(unique =>
unique
.On<ConstraintsDeclarativeIndexProjectCreated>(e => e.Name)
.RemovedWith<ConstraintsDeclarativeIndexProjectRemoved>());
}

View C# snippet source on GitHub

The name belongs to the project event source. Appending that same name again for the same project is allowed; a different project cannot claim it while it is held. Continue with Unique property constraints to choose how long values stay reserved.

The .NET client’s default artifact discovery finds IConstraint implementations in the assemblies it scans and registers their definitions with the Kernel during client startup. You do not need to register each class separately when using that discovery.