Skip to content
Back to skills

Ddd Dotnet

ASecurity

The .NET realization of tactical DDD (see the `ddd` skill for the principles). Use when writing or reviewing C# domain code: value objects and their factories, aggregates and their From/Create, which validator a value object or an aggregate builds and how it runs it, the domain exception family and its codes, collecting events on the root, or giving an aggregate its DbContext. It encodes the base types of a DDD library, the four-factory surface (From, FromOrNull, Create, CreateOrNull) and why...

  • 2 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 3, 2026
ai-agentsc#testinggitapi

Works with

  • api

Security analysis

A100/100

Scanned December 4, 2026

npx -y skills add JorgeCostaMacia/code-harness --skill ddd-dotnet --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Ddd Dotnet?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Ddd Dotnet
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/jorgecostamacia-ddd-dotnet-code-harness/badge)](https://www.skillsdirectory.com/skills/jorgecostamacia-ddd-dotnet-code-harness)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: ddd-dotnet
description: >-
  The .NET realization of tactical DDD (see the `ddd` skill for the
  principles). Use when writing or reviewing C# domain code: value objects
  and their factories, aggregates and their From/Create, which validator a
  value object or an aggregate builds and how it runs it, the domain
  exception family and its codes, collecting events on the root, or giving
  an aggregate its DbContext. It encodes the base types of a DDD library,
  the four-factory surface (From, FromOrNull, Create, CreateOrNull)
  and why every one is declared, Convert as the one place a value is
  altered, no coercion and no defaults on a value object, the aggregate rule
  (From cascades, Create seals), a UUIDv7 code for each exception, and one
  DbContext per aggregate as its accessor. How a validator's rules are
  written is in `validation-dotnet`.
---

# DDD in .NET

The .NET *how* of the model defined in `ddd` (load it for the *why*). `validation-dotnet` says how to write a validator: its rules, its messages and its composition. This skill says which validator each domain type has and how the type runs it.

## The base types

The building blocks come from a DDD library: a base for each kind of value object, an aggregate base that collects events, the entity and domain-event markers, and a domain exception hierarchy. Derive from them, and never redeclare them. This family uses the `JorgeCostaMacia.DDD.*` packages: [their docs](https://github.com/JorgeCostaMacia/ddd-dotnet/tree/main/docs) list each base type, what its validator checks and its exact API, and its `samples/Shop` shows a whole module.

## Value objects

A value object is a `sealed record` deriving from its base, one folder per field — `Domain/<Field>/` holding `<Aggregate><Field>`, its `<Aggregate><Field>Validator` and its `<Aggregate><Field>ValidationException`. All of them flat at the root of `Domain/`: no `ValueObjects/` grouping.

```csharp
internal sealed record PedidosReferencia : LongValueObject
{
    // HYDRATE — raw assignment, no conversion, no validation: ORMs and deserializers only.
    public PedidosReferencia(long value) : base(value) { }

    // CONVERT — materializes through Convert, unvalidated: the path composites build their parts with.
    public static new PedidosReferencia From(long value) => new PedidosReferencia(Convert(value));
    public static new PedidosReferencia? FromOrNull(long? value) => value is null ? null : From(value.Value);

    // CREATE — nothing invalid escapes it.
    public static new PedidosReferencia Create(long value)
    {
        PedidosReferencia vo = From(value);
        vo.Validate();

        return vo;
    }

    public static new PedidosReferencia? CreateOrNull(long? value)
    {
        PedidosReferencia? vo = FromOrNull(value);
        vo?.Validate();

        return vo;
    }

    private void Validate() => PedidosReferenciaValidator.Create().ValidateAndThrow(this);
}
```

- **Declare all four factories, always** — whatever the field's nature. The bases declare all four as public statics, so a factory that the type does not declare is still reachable and answers wrongly. Without its own declaration, `XId.CreateOrNull(5L)` returns the *base* type and runs only the base validator. The field's own rule does not run, and nothing reports it. `new` is mandatory on each, and the compiler proves the *modifier* both ways: `CS0108` without it, `CS0109` where it hides nothing. The compiler cannot prove that the type *declares* a factory. An undeclared factory resolves to the base's at any call site that does not demand the derived type. For example, `XEstado.Create(x).Value` in a predicate compiles and skips the rule. The aggregate pins `From`/`FromOrNull`, because its typed properties refuse the base (`CS0266`). `Create`/`CreateOrNull` on a payload VO have no production caller, so a test pins them — see *Testing this model*.
- **Optionality lives in the `OrNull` sibling, never in the return type**: `From`/`Create` always return non-null. `FromOrNull` is the one place that looks at the input (`value is null ? null : From(value.Value)`; a string VO writes `From(value)`, since `string?` has no `.Value`). `CreateOrNull` branches on **what `FromOrNull` returned** (`vo?.Validate()`), never on the input again. This way, it stays correct if a `From` ever maps a sentinel to absence, and it never gives the validator a null.
- **One input type per VO**, the base's natural primitive. A second suffixed overload (`FromOrNull(string?)` and `FromOrNull(int?)`) makes `FromOrNull(null)` ambiguous (`CS0121`). The call site converts any other primitive.
- **The type reaches its validator through one `private void Validate()`**; the local is `vo`.

### Convert — the one place a value is altered

The base's `protected static Convert` is the only place where a value changes on its way in. It converts the input to **the base's representation**: `StringValueObject` trims, `DateTimeUtcValueObject` yields an instant in UTC. A derived VO whose type represents something else **hides it** — `private static new` — and every factory picks it up:

```csharp
// fidelity: a layer that only stores what arrives keeps the source's text as it came
private static new string Convert(string value) => value;

// the store keeps microseconds: one value in memory, on the wire and in the table
private static new DateTime Convert(DateTime value)
{
    DateTime utc = DateTimeUtcValueObject.Convert(value);
    return new DateTime(utc.Ticks - (utc.Ticks % TimeSpan.TicksPerMicrosecond), DateTimeKind.Utc);
}
```

- A layer states its policy when it hides `Convert`. Keep the policy uniform across the layer: when the layer keeps the source's text, every string VO of it passes through, not only one of them.
- Calls *inside* the base still bind to the base's overloads — hiding only affects the derived type's factories.
- A conversion **never alters a value silently** beyond its rule: no comma dropped as a thousands separator, no fraction truncated into an integer. When the input is not the type, it throws.

### No coercion, no defaults

- **A VO never pulls a value into range.** Out of range is a caller's mistake and its `Create` throws the typed exception.
- **No `Default` and no public `Max`.** A default is call-site policy; a public bound is an invitation to clamp against it. The bound is a literal in the validator, pinned from both sides (see `validation-dotnet`).
- **A base rejects only what is not the type** — and most bases check nothing (`validation-dotnet` lists what each one does). Policy (not empty, a range, a format, a closed list) lives in the derived VO's validator.

### A composite value object

A VO made of other VOs (a page range of two page numbers) is a plain `IValueObject` record holding its parts, not a derived base. Its validator runs each part's own validator plus the cross rule (`start <= end`), which inheriting could not do.

## Aggregates

```csharp
internal sealed class Pedidos : Aggregate
{
    public long Id { get; init; }                          // the identity (see ddd: it may stay a primitive)
    public PedidosReferencia? Referencia { get; set; }     // optional field, nullable VO
    public PedidosUrgente Urgente { get; set; } = null!;

    private Pedidos() { }                                   // ORM materialization

    public Pedidos(                                        // hydration
        long id,
        PedidosReferencia? referencia,
        PedidosUrgente urgente)
    {
        Id = id;
        Referencia = referencia;
        Urgente = urgente;
    }

    // FROM cascades: every part through ITS From — nothing validated, nothing thrown yet.
    public static Pedidos From(
        long id,
        long? referencia,
        bool urgente)
        => new Pedidos(
            id,
            PedidosReferencia.FromOrNull(referencia),
            PedidosUrgente.From(urgente));

    // CREATE seals: one composed validation, one exception with every failure.
    public static Pedidos Create(
        long id,
        long? referencia,
        bool urgente)
    {
        Pedidos aggregate = From(
            id,
            referencia,
            urgente);
        aggregate.Validate();

        return aggregate;
    }

    private void Validate() => PedidosValidator.Create().ValidateAndThrow(this);
}
```

- The root is an `internal sealed class` deriving `Aggregate` (identity, not value semantics — so a class, not a record). Fields that change are `set`; the identity and what never changes after creation are `init`.
- **The aggregate never calls its parts' `Create`** — that would throw on the first invalid part alone. `From` cascades through the parts' `From`/`FromOrNull`; `Create` validates the whole once (see *Validating the model*).
- **The nullability of each factory call matches its property**: `XField.FromOrNull(...)` for an optional field, `XField.From(...)` for a required one. Add a field, keep both sides in step.

## Validating the model

Every value object and every aggregate has its own `<X>Validator` and `<X>ValidationException`, next to it in its folder.

- **The type builds its validator with `Create()` and never resolves it from DI.** A type validates inside its own static `Create`, where there is no container. Its rules are pure, so there is nothing to inject. `XValidator.Create()` assembles the whole chain, and the type reaches it through one `private void Validate() => XValidator.Create().ValidateAndThrow(this);`.
- **Only `Create` validates.** `From` and the hydration constructor never validate. `From` builds a composite from unvalidated parts, and the hydration of N rows must not validate them again.
- **A value object's validator `Include`s its base's** (`Include(DateTimeUtcValueObjectValidator.Create())` through the constructor) and adds the field's own rule, so the base's type checks always run. Its exception derives the base's (`DateTimeValueObjectValidationException`…).
- **The aggregate's validator composes its parts**: one `SetValidator` per value-object property, plus the aggregate's own cross-field rules. For an optional property, the rule selects `v.Part!` and guards it with `.When(v => v.Part is not null)`. One `ValidateAndThrow` in `Create` reports every failure, with its property path, in one `<X>ValidationException`.

  ```csharp
  // in PedidosValidator's constructor
  PedidosReferenciaValidator referencia = PedidosReferenciaValidator.Create();

  RuleFor(v => v.Referencia!)
      .SetValidator(referencia)
      .When(v => v.Referencia is not null);

  RuleFor(v => v.Urgente)
      .SetValidator(PedidosUrgenteValidator.Create());

  RuleFor(v => v.Referencia)                   // the aggregate's own cross-field rule
      .NotNull()
      .When(v => v.Urgente.Value);
  ```

- **Which layer holds a content rule** follows `ddd`. In a layer that only stores what arrives, a payload VO has a validator that only `Include`s its base's. The field's rule, such as a length or a format, lives in the VO of the layer that owns the content. The storing layer's own rules are on its identity and its own metadata.

## The exception family

Each concept ships its typed exceptions, one file each, deriving the library's bases: `<X>ValidationException` (raised by its validator), `<X>NotFoundException`, `<X>ExistException`.

- Each carries a **fixed GUID code**, a literal in its convenience constructor, so occurrences trace across logs and responses whatever the wording. The code is a **UUIDv7** (`Guid.CreateVersion7()`). Whoever writes the file mints a new one for each exception type and never copies it from a neighbour. If a generator stamps one GUID into every file it writes, seventy exceptions share one code. That code then identifies none of them. Nothing in the language checks it, so the host suite does: one convention test asserts every exception's code is distinct across the solution (see `testing-dotnet`).
- Two constructors: the full tuple (transport) and the convenience one producers use.

## Events

The root collects what happened as `IDomainEvent`s through `AddEvent(...)`. In this family, the event is the contract's own: the bus contract's event implements the library's domain-event marker, so the root's list takes it as it is (see `ddd`: the published events *are* the domain events). This is an **accepted core coupling, declared here**: the use case builds the contract's event and adds it to the root (`aggregate.AddEvent(new <Module>LoadedEvent(…))`), so the `Domain/` folder never names a contract or a transport type. Whoever persists the root takes the events with `PullEvents()` **after** a successful save, so no event escapes a failed operation. How they reach the broker is the bus skill's.

## The aggregate's accessor

**One `DbContext` per aggregate**, internal to its module, its `DbSet` named `<X>Repository`: the per-aggregate accessor `ddd` asks for. Application uses it as-is — an accepted core coupling, with no repository port around it. How the model maps to the tables (value objects, keys, converters) is persistence, not this skill's.

## Testing this model

- Composition tests use `From` (it skips the validators and keeps the test free of unrelated field rules); rule tests use `Create`.
- Every VO with a rule of its own: its red case on the typed exception, and the bound from both sides.
- `From`/`FromOrNull` both directions on the aggregate: every optional part materialized when supplied, every one null when not.
- A `Convert` of its own (a truncation, a kind) has its own test: without it, moving the VO to another base passes everything else.
- **A VO with no rule and no `Convert` of its own has no test file of its own.** Its tests would pin the same things for every VO of its kind. They pin the four factories, declared on the type and returning it, and the layer's `Convert` policy. A layer that keeps the source's text passes its strings through; any other layer trims them. So one **convention test per module** enumerates the module's value objects and pins both things for all of them (`testing-dotnet` has the realization). The day it gains a rule or a `Convert`, it gains its file.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.