Koto.Domain
0.5.0-preview.3
See the version list below for details.
dotnet add package Koto.Domain --version 0.5.0-preview.3
NuGet\Install-Package Koto.Domain -Version 0.5.0-preview.3
<PackageReference Include="Koto.Domain" Version="0.5.0-preview.3" />
<PackageVersion Include="Koto.Domain" Version="0.5.0-preview.3" />
<PackageReference Include="Koto.Domain" />
paket add Koto.Domain --version 0.5.0-preview.3
#r "nuget: Koto.Domain, 0.5.0-preview.3"
#:package Koto.Domain@0.5.0-preview.3
#addin nuget:?package=Koto.Domain&version=0.5.0-preview.3&prerelease
#tool nuget:?package=Koto.Domain&version=0.5.0-preview.3&prerelease
Koto.Domain
What a domain model is built from: aggregates, value objects, typed identifiers, events, and results instead of exceptions. No dependencies. Part of the Koto suite.
Install
dotnet add package Koto.Domain --prerelease
What's included
| Type | Purpose |
|---|---|
AggregateRoot<TId> |
An aggregate that keeps its state and records the domain events it raised |
EventSourcedAggregateRoot<TId> |
An aggregate whose state is its events; storage lives in infrastructure (e.g. Koto.EventSourcing.Marten) |
Entity<TId> |
Equality by identifier |
ValueObject |
Equality by components, for value objects that need a custom one; a record is enough otherwise |
StronglyTypedId<T> |
OrderId instead of Guid |
Result / Result<T> |
The outcome of an operation: success (with a value) or every error that stopped it |
Error |
Abstract — each error is a record of its own with a stable code; its properties are its data |
ErrorList<TError> |
The errors of a failed result; returning it propagates all of them |
Errors.General |
A few shared errors: NotFound, ValueIsRequired, InvalidLength, … |
IDomainEvent / DomainEvent |
What happened inside the service |
Repositories and the unit of work are ports of the application layer:
IRepository<TAgg, TId>andIUnitOfWorklive in Koto.Application. The domain knows nothing about storage.
An aggregate
A rule is one line: a condition and the error it returns. Success is a value or Result.Ok.
public static Result<Order> Place(CustomerId customerId, IReadOnlyList<OrderLine> lines, DateTimeOffset now)
{
if (lines.Count == 0) return new OrderHasNoLines();
if (lines.Count > MaxLines) return new OrderHasTooManyLines(MaxLines);
var order = new Order(OrderId.New(), customerId, lines, placedAt: now);
order.AddDomainEvent(new OrderPlacedDomainEvent(order.Id, customerId));
return order;
}
public Result Cancel(string reason, DateTimeOffset now)
{
if (IsCancelled) return new OrderAlreadyCancelled(Id);
if (now > CancellableUntil) return new CancellationWindowClosed(CancellableUntil);
IsCancelled = true;
AddDomainEvent(new OrderCancelledDomainEvent(Id, reason));
return Result.Ok;
}
private DateTimeOffset CancellableUntil => PlacedAt + CancellationWindow;
The whole class, with its constructor and state:
samples/Shop/Shop.Domain/Orders/Order.cs.
Habits that keep it readable:
- The numbers a rule uses are named constants with a summary (
Order.MaxLines,Order.CancellationWindow). - Time comes in as a parameter (
DateTimeOffset now); the handler gets it fromTimeProvider. The model never asks the clock. AddDomainEvent(...)records what happened. Events are delivered when the unit of work commits.
Errors are types
public sealed record OrderHasNoLines()
: Error("shop.order.no-lines", "An order needs at least one line.");
public sealed record OrderHasTooManyLines(int MaxLines)
: Error("shop.order.too-many-lines", $"An order can hold at most {MaxLines} lines.");
public sealed record OrderAlreadyCancelled(OrderId OrderId)
: Error("shop.order.already-cancelled", "The order is already cancelled.");
public sealed record CancellationWindowClosed(DateTimeOffset ClosedAt)
: Error("shop.order.cancellation-window-closed", "It is too late to cancel this order.");
Erroris abstract: there is nonew Error(code, message). Define the record where the condition is detected — in the domain, or in the application layer when only a handler can know (OrderNotFound).- A record's properties are the data it promises. They reach the client as
details({ "orderId": "7c9e…" }— aStronglyTypedIdis sent as its value). - A code is
context.entity.problem: at least three kebab-case segments, validated when the error is created. The HTTP status follows from it:*.not-found→ 404,*.already-*→ 409. Koto.Testing'sErrorCatalog.ShouldBeValid(assembly)checks every code and its uniqueness in one test.
A value object
The only way in is a factory that can refuse, so a value of this type is always valid.
/// <summary>The address a customer is known by.</summary>
public sealed record Email
{
/// <summary>The longest address the shop accepts.</summary>
public const int MaxLength = 150;
private Email(string address) => Address = address;
public string Address { get; }
public static Result<Email> Create(string? address)
{
if (string.IsNullOrWhiteSpace(address)) return new EmailIsRequired();
if (address.Length > MaxLength) return new EmailIsTooLong(MaxLength);
if (!address.Contains('@')) return new EmailIsMalformed();
return new Email(address.Trim().ToLowerInvariant());
}
}
Results
// propagate every error of a failed result
var email = Email.Create(command.Email);
if (email.IsFailure) return email.Errors;
// several factories at once — all errors are collected
var parsed = Result.Combine(Email.Create(dto.Email), Name.Create(dto.Name));
if (parsed.IsFailure) return parsed.Errors;
var (address, name) = parsed.Value;
// a collection — every bad element is reported
Result<IReadOnlyList<OrderLine>> lines = Result.Traverse(dto.Lines, line => OrderLine.Create(line.Product, line.Quantity));
FirstError is the headline of a failure — for a log line or a test. To pass a failure on, return
Errors: returning FirstError would drop the rest, and the compiler says so (KOTO002).
Result<T> also has Map, Bind, Tap, Ensure, Match and their async forms for those who prefer chains.
An event-sourced aggregate
State changes only by raising events; Apply is the one place that mutates it.
public sealed class Account : EventSourcedAggregateRoot<AccountId>
{
private Account() { }
public int Balance { get; private set; }
public Result Withdraw(int amount)
{
if (amount > Balance) return new InsufficientFunds(Balance, amount);
RaiseEvent(new CoinsWithdrawn(amount));
return Result.Ok;
}
protected override void Apply(IDomainEvent @event)
{
switch (@event)
{
case CoinsDeposited deposited: Balance += deposited.Amount; break;
case CoinsWithdrawn withdrawn: Balance -= withdrawn.Amount; break;
}
}
}
The base class is part of this package, so an event-sourced domain project references Koto.Domain only.
Analyzers
The package carries two compiler checks. Every project that references a Koto package gets them; there is nothing to install.
| Rule | Reported when | Write instead |
|---|---|---|
KOTO001 |
A result is discarded: order.Cancel(reason, now); on a line of its own, with or without await |
Return it or check it. _ = order.Cancel(reason, now); says it is dropped on purpose |
KOTO002 |
FirstError is returned as the failure: return email.FirstError; |
return email.Errors; |
Both are errors, not warnings: a refusal nobody reads is a bug. A result is anything that implements
IResultBase — Result, Result<T>, AppResult, AppResult<T> — also inside a Task or a ValueTask.
A project can lower a rule in its .editorconfig: dotnet_diagnostic.KOTO001.severity = warning.
Upgrading
From 0.4: Error became abstract and Result<T>.Error became FirstError. Within 0.5 (preview.2):
Result<Unit> is Result and ends with return Result.Ok;, and EventSourcedAggregateRoot<TId> moved
here from Koto.EventSourcing.Marten. In preview.3 the analyzers start reporting discarded
results and returned FirstErrors as errors. The step-by-step guide with before/after code:
docs/migrations/0.4-to-0.5.md.
License
MIT
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | 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. |
-
net10.0
- No dependencies.
NuGet packages (8)
Showing the top 5 NuGet packages that depend on Koto.Domain:
| Package | Downloads |
|---|---|
|
Koto.Application
CQRS dispatcher, pipeline behaviors, and cross-service integration abstractions for .NET microservices. Depends only on Koto.Domain and Microsoft.Extensions abstractions. |
|
|
Koto.Validation
FluentValidation extensions for Koto: MustBeValueObject, ListMustContainNumberOfItems, the ValidationBehavior pipeline behavior (enriched errors per field) and AddValidationBehavior ordering. |
|
|
Koto.EventSourcing.Marten
Event Sourcing on PostgreSQL via Marten: event-sourced repository, MartenUnitOfWork, inline and async projections. The aggregate base (EventSourcedAggregateRoot) lives in Koto.Domain, so domain projects never reference this package. |
|
|
Koto.Infrastructure.Http
Anti-Corruption Layer for HTTP calls between services: typed ServiceHttpClient base, Result-mapped error handling, correlation ID propagation, and standard resilience. |
|
|
Koto.Infrastructure.EFCore
EF Core 10 integration for Koto DDD: generic repository, strongly-typed ID converters, pagination, and Wolverine outbox wiring. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.5.0-preview.9 | 73 | 11/30/2026 |
| 0.5.0-preview.8 | 80 | 11/30/2026 |
| 0.5.0-preview.7 | 76 | 11/29/2026 |
| 0.5.0-preview.6 | 75 | 11/29/2026 |
| 0.5.0-preview.5 | 81 | 11/29/2026 |
| 0.5.0-preview.4 | 86 | 11/29/2026 |
| 0.5.0-preview.3 | 82 | 11/29/2026 |
| 0.5.0-preview.2 | 83 | 11/29/2026 |
| 0.5.0-preview.1 | 117 | 11/8/2026 |
| 0.4.0 | 303 | 7/21/2026 |
| 0.3.0-preview.15 | 136 | 7/21/2026 |
| 0.3.0-preview.14 | 135 | 7/21/2026 |
| 0.3.0-preview.13 | 127 | 7/21/2026 |
| 0.3.0-preview.12 | 128 | 7/21/2026 |
| 0.3.0-preview.11 | 134 | 7/21/2026 |
| 0.3.0-preview.10 | 119 | 7/21/2026 |
| 0.3.0-preview.9 | 127 | 7/21/2026 |
| 0.3.0-preview.8 | 131 | 7/21/2026 |
| 0.3.0-preview.7 | 125 | 7/21/2026 |
| 0.3.0-preview.6 | 113 | 7/20/2026 |
0.5.0-preview.3 — the compiler keeps a refusal from getting lost (ADR-028): two analyzers ship inside Koto.Domain and reach every project that references a Koto package. KOTO001: a result is discarded (order.Cancel(reason, now); on a line of its own). KOTO002: FirstError is returned as the failure instead of Errors. Both are errors, so existing code may stop building; migration guide: https://github.com/arigatory/Koto/blob/main/docs/migrations/0.4-to-0.5.md