Koto.Domain 0.5.0-preview.5

This is a prerelease version of Koto.Domain.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package Koto.Domain --version 0.5.0-preview.5
                    
NuGet\Install-Package Koto.Domain -Version 0.5.0-preview.5
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Koto.Domain" Version="0.5.0-preview.5" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Koto.Domain" Version="0.5.0-preview.5" />
                    
Directory.Packages.props
<PackageReference Include="Koto.Domain" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Koto.Domain --version 0.5.0-preview.5
                    
#r "nuget: Koto.Domain, 0.5.0-preview.5"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Koto.Domain@0.5.0-preview.5
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Koto.Domain&version=0.5.0-preview.5&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Koto.Domain&version=0.5.0-preview.5&prerelease
                    
Install as a Cake Tool

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> and IUnitOfWork live 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 from TimeProvider. 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.");
  • Error is abstract: there is no new 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…" } — a StronglyTypedId is 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's ErrorCatalog.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. The factory parses: it turns a string into an Email or into the reason the string is not one. It has no "required" error — whether an email is needed is the rule of whoever needs it (an aggregate takes an Email that cannot be null; for a request field see Koto.Validation).

/// <summary>The address a customer is known by.</summary>
public sealed record Email
{
    private Email(string address) => Address = address;

    public string Address { get; }

    public string Domain => Address.Split('@')[^1];

    /// <summary>The shop's own people write from the shop's domain.</summary>
    public bool BelongsToStaff => Domain == "shop.example";

    public static Result<Email> Create(string address)
    {
        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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • 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
Loading failed

0.5.0-preview.5 — bug fix: ListMustContainNumberOfItems threw on a missing list (HTTP 500); new rule MustBePresent() reports a missing value that is not a value object as general.value.is-required, bound to the field. Since preview.4: a value object's factory only parses, MustBeValueObjectOrNull for optional values; analyzers KOTO001/KOTO002. Migration guide: https://github.com/arigatory/Koto/blob/main/docs/migrations/0.4-to-0.5.md