<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Ddd on Russell ‘Russ’ Frith</title><link>https://russfrith.com/tags/ddd/</link><description>Recent content in Ddd on Russell ‘Russ’ Frith</description><generator>Hugo</generator><language>en-us</language><lastBuildDate>Tue, 01 Dec 2026 09:57:28 -0500</lastBuildDate><atom:link href="https://russfrith.com/tags/ddd/index.xml" rel="self" type="application/rss+xml"/><item><title>Domain-Driven Design: The Parts We Skip or Get Wrong</title><link>https://russfrith.com/posts/ddd-misunderstood-concepts/</link><pubDate>Tue, 01 Dec 2026 09:57:28 -0500</pubDate><guid>https://russfrith.com/posts/ddd-misunderstood-concepts/</guid><description>Bounded contexts, aggregates, and the other Domain-Driven Design ideas that developers use loosely, with precise definitions, C# examples, and ways to spot misuse</description><content:encoded><![CDATA[<p>Plenty of developers say &ldquo;aggregate root&rdquo; or &ldquo;bounded context&rdquo; in design meetings while being a little vague about what they mean. The words from Eric Evans&rsquo; <em>Domain-Driven Design</em> (the blue book, published in 2003) spread much further than the ideas behind them.[<a href="#references">1</a>] You can have folders named <code>Aggregates</code>, <code>ValueObjects</code>, and <code>Repositories</code> and still have a model that nobody in the business would recognize.</p>
<p>The usual cause is adopting the tactical patterns (entities, value objects, repositories) and leaving the strategic design (language, boundaries, and where to spend effort) on the shelf. The tactical patterns look like code, so they&rsquo;re easy to pick up. The strategic ones require talking to people, and they decide whether the tactical ones are drawn in the right places. I&rsquo;ll give bounded contexts and aggregates the most attention, using C# and a fictional online retailer.</p>
<h2 id="bounded-contexts">Bounded Contexts</h2>
<p><strong>A bounded context is an explicit boundary within which one domain model, and the language that goes with it, applies consistently.</strong></p>
<p>Inside the boundary, a term has one meaning and the rules attached to it don&rsquo;t contradict each other. Outside it, all bets are off. The same word may mean something else, and that&rsquo;s fine as long as you know where the line is and translate when you cross it.</p>
<p>Some differences are obvious. In a store, an order is a request to buy something. In the army, it&rsquo;s an instruction an officer gives a soldier. Nobody would try to serve both with one <code>Order</code> class. The trouble comes from meanings close enough to look identical.</p>
<p>Suppose a customer buys a desk and a lamp in one checkout. The lamp is in stock in Newark, and the desk is in a warehouse in Reno. Ask three parts of the business about &ldquo;the order&rdquo;:</p>
<ul>
<li><strong>Ordering</strong> sees one order. It&rsquo;s the customer&rsquo;s request to buy two items at an agreed price, and it&rsquo;s placed as soon as checkout succeeds.</li>
<li><strong>Fulfillment</strong> sees two orders, one for each warehouse to pick, pack, and ship. The lamp&rsquo;s order can be finished while the desk&rsquo;s hasn&rsquo;t started.</li>
<li><strong>Billing</strong> sees something to collect money for. It might charge as each box leaves, and it cares about payments and refunds, not shelves.</li>
</ul>
<p>Now ask whether the order is complete. Ordering might say yes because the customer has checked out, Fulfillment says half of it is, and Billing says no until the second charge clears. All three are right. A single <code>Order</code> class would need one <code>Status</code> property to answer three different questions. Separate models let each context have its own states and rules, linked by an order ID.</p>
<p>The alternative, one model for the whole company, sounds efficient and ages badly. Every department&rsquo;s needs pile onto the same classes until nobody can change anything without asking everybody.</p>
<h3 id="one-word-four-meanings">One Word, Four Meanings</h3>
<p>Take &ldquo;product.&rdquo;</p>
<table>
  <thead>
      <tr>
          <th>Context</th>
          <th>What &ldquo;product&rdquo; means there</th>
          <th>Data it cares about</th>
          <th>A rule it owns</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>Catalog</td>
          <td>Something a customer can find and read about</td>
          <td>Name, description, images, category</td>
          <td>A listing can&rsquo;t go live without a description</td>
      </tr>
      <tr>
          <td>Inventory</td>
          <td>Units we physically hold and can promise</td>
          <td>SKU, location, quantity on hand</td>
          <td>We can&rsquo;t reserve more than we have</td>
      </tr>
      <tr>
          <td>Pricing</td>
          <td>Something with a price at a point in time</td>
          <td>Price lists, currency, effective dates</td>
          <td>Two prices can&rsquo;t be active for the same market at once</td>
      </tr>
      <tr>
          <td>Shipping</td>
          <td>A thing that has to fit in a box</td>
          <td>Weight, dimensions, hazard class</td>
          <td>Some hazardous items can&rsquo;t go by air</td>
      </tr>
  </tbody>
</table>
<p>The tempting design is one <code>Product</code> class with every column from that table, most of them irrelevant (and often null) for any given use. Someone adds <code>IsActive</code>, and four teams read it four ways.</p>
<p>With bounded contexts, each gets its own model, containing only what its rules need. Catalog has a <code>Product</code>, while Inventory talks about stock items. They share an identifier, such as the SKU, not a class. If the product name shows up in more than one context, that&rsquo;s a copy with a known owner (Catalog), kept current by a message or a query. It&rsquo;s a far smaller problem than one class serving four masters.</p>
<h3 id="finding-the-boundaries">Finding the Boundaries</h3>
<p><strong>Ubiquitous language is the shared vocabulary that developers and domain experts use, within one context, in conversation, documents, and code alike.</strong></p>
<p>Teams tend to treat this as a naming convention, but it&rsquo;s also the best boundary detector you have. &ldquo;Ubiquitous&rdquo; means everywhere inside a context, not one dictionary for the enterprise. When you try to define a term and the experts start saying &ldquo;well, not for us,&rdquo; you&rsquo;ve probably found an edge. Listen for these:</p>
<ul>
<li><strong>The same word with different meanings.</strong> &ldquo;Customer&rdquo; to Sales might be a prospect, and to Billing it&rsquo;s whoever pays the invoice.</li>
<li><strong>Different words for the same thing.</strong> If the warehouse says &ldquo;pick&rdquo; and the storefront says &ldquo;fulfill,&rdquo; check whether they mean the same step. They may be two models of one physical event.</li>
<li><strong>Different experts.</strong> If a question about pricing and a question about packing go to different people, one model is unlikely to serve both well.</li>
<li><strong>Handoffs.</strong> Where work moves between departments and someone re-keys or reinterprets it, there is usually a translation your software should make explicit.</li>
</ul>
<p>None of these is proof. Boundaries are design decisions, and you will move some of them as you learn.</p>
<h3 id="what-a-bounded-context-is-not">What a Bounded Context Is Not</h3>
<ul>
<li><strong>Not a microservice.</strong> A context can be one module in a monolith, and often should start that way. It can also be implemented by more than one deployable. The context is about where a model is valid; a service is about how software is deployed. Evans has called equating the two an oversimplification.[<a href="#references">2</a>] Several services designed and changed together can form one context. The trouble starts when you treat them as independent and they still have to change in lockstep.</li>
<li><strong>Not a module or namespace.</strong> Those are fine tools for enforcing a boundary, but creating a <code>Pricing</code> folder does nothing if its classes reference <code>Catalog.Product</code> directly.</li>
<li><strong>Not a team.</strong> One team can own several contexts. Two teams sharing one context is possible too, though it takes constant coordination to keep the model from splitting.</li>
<li><strong>Not a subdomain.</strong> A subdomain is an area of the business, such as billing or shipping, and it exists whether or not you write any software. A bounded context is a line you draw around a model in that software. One context per subdomain is a good aim, but the two often don&rsquo;t match. A legacy system that handles both billing and shipping with a single <code>Order</code> model is one context spanning two subdomains. During a rewrite, an old and a new billing system, each with its own model, can be two contexts inside one subdomain.[<a href="#references">2</a>]</li>
</ul>
<h2 id="context-maps-and-anticorruption-layers">Context Maps and Anticorruption Layers</h2>
<p><strong>A context map is an honest picture of which bounded contexts exist and how each pair that interacts is related, technically and organizationally.</strong></p>
<p>The organizational part is what gets dropped. Boxes and arrows showing API calls don&rsquo;t say who gets to change the contract. Here are some of the relationships Evans describes:</p>
<ul>
<li><strong>Customer/supplier.</strong> The downstream team&rsquo;s needs are part of the upstream team&rsquo;s planning.</li>
<li><strong>Conformist.</strong> The downstream team adopts the upstream model as it is, usually because it has no say. That can be a reasonable choice when the upstream model is good enough.</li>
<li><strong>Anticorruption layer.</strong> The downstream team translates the upstream model into its own.</li>
<li><strong>Shared kernel.</strong> Two contexts share a small piece of model and code, and neither changes it without the other.</li>
<li><strong>Separate ways.</strong> The integration isn&rsquo;t worth its cost, so you don&rsquo;t build it.</li>
</ul>
<p><strong>An anticorruption layer is translation code that lets your model use another system without adopting that system&rsquo;s concepts.</strong></p>
<p>Suppose Inventory reads from an old warehouse system. It counts full cases, tracks held units separately, lets counts drift below zero, and packs meaning into one-letter status codes. Inventory only wants to know how many units it can sell. The translator is the only place that knows how to get from one to the other:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#75715e">// The legacy system&#39;s shape. Nothing outside this layer should see it.</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">record</span> <span style="color:#a6e22e">WmsStockRow</span>(
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">string</span> ItemCode,
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">int</span> CasesOnHand,   <span style="color:#75715e">// can be negative until the next stock count</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">int</span> UnitsPerCase,
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">int</span> HeldUnits,     <span style="color:#75715e">// set aside, but still included in the case count</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">string</span> StatusCode);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// What Inventory cares about, in its own terms.</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">record</span> <span style="color:#a6e22e">StockSnapshot</span>(Sku Sku, Quantity Sellable);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">WmsTranslator</span>
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> StockSnapshot Translate(WmsStockRow row)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (row.UnitsPerCase &lt;= <span style="color:#ae81ff">0</span>)
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> InvalidDataException(<span style="color:#e6db74">$&#34;Bad case size for &#39;{row.ItemCode}&#39;.&#34;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> physicalUnits = <span style="color:#66d9ef">checked</span>(Math.Max(row.CasesOnHand, <span style="color:#ae81ff">0</span>) * row.UnitsPerCase);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> unheldUnits = Math.Max(physicalUnits - row.HeldUnits, <span style="color:#ae81ff">0</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> sellableUnits = row.StatusCode <span style="color:#66d9ef">switch</span>
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            <span style="color:#e6db74">&#34;A&#34;</span> =&gt; unheldUnits, <span style="color:#75715e">// active</span>
</span></span><span style="display:flex;"><span>            <span style="color:#e6db74">&#34;D&#34;</span> =&gt; unheldUnits, <span style="color:#75715e">// discontinued, but we sell what&#39;s left</span>
</span></span><span style="display:flex;"><span>            <span style="color:#e6db74">&#34;Q&#34;</span> =&gt; <span style="color:#ae81ff">0</span>,           <span style="color:#75715e">// quarantined</span>
</span></span><span style="display:flex;"><span>            _ =&gt; <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> NotSupportedException(<span style="color:#e6db74">$&#34;Unknown WMS status &#39;{row.StatusCode}&#39;.&#34;</span>)
</span></span><span style="display:flex;"><span>        };
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> StockSnapshot(<span style="color:#66d9ef">new</span> Sku(row.ItemCode), <span style="color:#66d9ef">new</span> Quantity(sellableUnits));
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>An adapter that copies <code>StatusCode</code> into a property on your domain class isn&rsquo;t an anticorruption layer. The foreign concept got in; it just has a nicer name. The layer also costs something to write and maintain, so use it where the other model would distort yours.</p>
<h2 id="core-domain-where-ddd-pays-off">Core Domain: Where DDD Pays Off</h2>
<p><strong>The core domain is the part of your domain model that sets the organization apart and therefore deserves your best design effort.</strong></p>
<p>Evans separates it from generic subdomains, which are necessary but not special. Later DDD writing, including Vaughn Vernon&rsquo;s, commonly adds supporting subdomains as a third category: specific to your business, but not what makes it competitive.[<a href="#references">3</a>]</p>
<table>
  <thead>
      <tr>
          <th>Subdomain type</th>
          <th>Retailer example</th>
          <th>Reasonable approach</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>Core</td>
          <td>Promising delivery dates from scattered stock</td>
          <td>Careful modeling, experienced people, frequent expert contact</td>
      </tr>
      <tr>
          <td>Supporting</td>
          <td>Managing supplier contact records</td>
          <td>Simple code, plain CRUD is often enough</td>
      </tr>
      <tr>
          <td>Generic</td>
          <td>Authentication, general ledger, sending email</td>
          <td>Buy it or use an established library</td>
      </tr>
  </tbody>
</table>
<p>Your table will differ. Pricing is core for one retailer and a spreadsheet import for another.</p>
<p>Teams often skip deciding which part is core, and it&rsquo;s expensive. They wrap a settings screen in aggregates and repositories, then run out of patience before reaching the part of the system where the rules are hard. If a feature validates input and writes a row, write that code and move on. DDD earns its cost where the rules are intricate, change often, and matter to the business. I made a related argument about matching structure to complexity in <a href="/posts/repository-pattern-ef-core-specifications/#where-this-loses-and-when-to-skip-it">In Defense of the Repository</a>.</p>
<h2 id="entities-and-value-objects">Entities and Value Objects</h2>
<p><strong>An entity is an object defined by a continuous identity that persists while its attributes change.</strong></p>
<p><strong>A value object is an immutable object defined entirely by its attributes, so two with equal values are interchangeable.</strong></p>
<p>A stock item is an entity. Its quantity changes all day and it&rsquo;s still the same stock item. A quantity of five is a value. Nobody cares which five.</p>
<p>Prefer value objects where identity doesn&rsquo;t matter. They can&rsquo;t be changed behind your back, they&rsquo;re easy to test, and they give rules a home. Without them, those rules get repeated wherever an <code>int</code> or <code>string</code> is passed around.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">record</span> <span style="color:#a6e22e">Sku</span>
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> Sku(<span style="color:#66d9ef">string</span> <span style="color:#66d9ef">value</span>)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        ArgumentException.ThrowIfNullOrWhiteSpace(<span style="color:#66d9ef">value</span>);
</span></span><span style="display:flex;"><span>        Value = <span style="color:#66d9ef">value</span>.Trim().ToUpperInvariant();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">string</span> Value { <span style="color:#66d9ef">get</span>; }
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">readonly</span> <span style="color:#66d9ef">record</span> <span style="color:#a6e22e">struct</span> Quantity
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> Quantity(<span style="color:#66d9ef">int</span> <span style="color:#66d9ef">value</span>)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        ArgumentOutOfRangeException.ThrowIfNegative(<span style="color:#66d9ef">value</span>);
</span></span><span style="display:flex;"><span>        Value = <span style="color:#66d9ef">value</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">int</span> Value { <span style="color:#66d9ef">get</span>; }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> Quantity <span style="color:#66d9ef">operator</span> +(Quantity a, Quantity b) =&gt; <span style="color:#66d9ef">new</span>(<span style="color:#66d9ef">checked</span>(a.Value + b.Value));
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> Quantity <span style="color:#66d9ef">operator</span> -(Quantity a, Quantity b) =&gt; <span style="color:#66d9ef">new</span>(a.Value - b.Value);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">bool</span> <span style="color:#66d9ef">operator</span> &gt;(Quantity a, Quantity b) =&gt; a.Value &gt; b.Value;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">bool</span> <span style="color:#66d9ef">operator</span> &lt;(Quantity a, Quantity b) =&gt; a.Value &lt; b.Value;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>These use get-only properties on purpose. A positional record gives you <code>init</code> accessors, so a <code>with</code> expression could produce a new value that skips the constructor&rsquo;s checks.</p>
<h3 id="record-or-value-object-base-class">Record or Value Object Base Class?</h3>
<p>I start with a record. The compiler writes equality and hashing for me. The catch is that some members, collections especially, compare by their own equality, so two records holding separate lists with identical items are not equal. For one unusual type, override <code>Equals(T)</code> and <code>GetHashCode</code>. A base class earns its place when many types need rules that records don&rsquo;t give you, and since a record can&rsquo;t inherit from an ordinary class, you&rsquo;re choosing one or the other.</p>
<p>For a single primitive with rules, such as <code>Quantity</code>, a <code>readonly record struct</code> is a good fit. It gets generated equality and doesn&rsquo;t need its own heap object. The condition is that <code>default</code> must be a valid value, because it skips your constructor. Zero is a fine quantity, while an empty SKU is not, so <code>Sku</code> stays a class. A struct also can&rsquo;t inherit from <code>ValueObject</code>.</p>
<p>The next two examples use <code>ShippingRestriction</code>, which records a hazardous item&rsquo;s hazard class and the transport modes it&rsquo;s banned from. If a record holds a collection, don&rsquo;t rely on the generated equality. Copy the collection in the constructor and compare its items:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">bool</span> Equals(ShippingRestriction? other) =&gt;
</span></span><span style="display:flex;"><span>    other <span style="color:#66d9ef">is</span> not <span style="color:#66d9ef">null</span>
</span></span><span style="display:flex;"><span>    &amp;&amp; HazardClass == other.HazardClass
</span></span><span style="display:flex;"><span>    &amp;&amp; BannedModes.SequenceEqual(other.BannedModes);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">override</span> <span style="color:#66d9ef">int</span> GetHashCode()
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> hash = <span style="color:#66d9ef">new</span> HashCode();
</span></span><span style="display:flex;"><span>    hash.Add(HazardClass);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">foreach</span> (<span style="color:#66d9ef">var</span> mode <span style="color:#66d9ef">in</span> BannedModes)
</span></span><span style="display:flex;"><span>        hash.Add(mode);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> hash.ToHashCode();
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>These are the two members you&rsquo;d add to a record version of <code>ShippingRestriction</code>, with the same constructor and properties as the class shown below.</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/implement-value-objects">Microsoft&rsquo;s guide</a> shows a base class where each type lists its equality components,[<a href="#references">4</a>] and <a href="https://enterprisecraftsmanship.com/posts/csharp-records-value-objects/">Vladimir Khorikov</a> prefers that style to records for the control it gives.[<a href="#references">5</a>] I have also used a base class that finds the properties through reflection and caches them, so new properties join equality automatically. Here is a small version written for this post:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">using</span> System.Collections;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">using</span> System.Collections.Concurrent;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">using</span> System.Diagnostics.CodeAnalysis;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">using</span> System.Reflection;
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">[AttributeUsage(AttributeTargets.Property)]</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">NotPartOfValueAttribute</span> : Attribute;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Tells the trimmer to keep public properties on this class and its subclasses</span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)]</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">abstract</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">ValueObject</span> : IEquatable&lt;ValueObject&gt;
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">readonly</span> ConcurrentDictionary&lt;Type, PropertyInfo[]&gt; Cache = <span style="color:#66d9ef">new</span>();
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">readonly</span> <span style="color:#66d9ef">object</span> Start = <span style="color:#66d9ef">new</span>(), End = <span style="color:#66d9ef">new</span>();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">bool</span> Equals(ValueObject? other) =&gt;
</span></span><span style="display:flex;"><span>        other <span style="color:#66d9ef">is</span> not <span style="color:#66d9ef">null</span>
</span></span><span style="display:flex;"><span>        &amp;&amp; other.GetType() == GetType()
</span></span><span style="display:flex;"><span>        &amp;&amp; Components().SequenceEqual(other.Components());
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">override</span> <span style="color:#66d9ef">bool</span> Equals(<span style="color:#66d9ef">object?</span> obj) =&gt; Equals(obj <span style="color:#66d9ef">as</span> ValueObject);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">override</span> <span style="color:#66d9ef">int</span> GetHashCode()
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> hash = <span style="color:#66d9ef">new</span> HashCode();
</span></span><span style="display:flex;"><span>        hash.Add(GetType());
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">foreach</span> (<span style="color:#66d9ef">var</span> component <span style="color:#66d9ef">in</span> Components())
</span></span><span style="display:flex;"><span>            hash.Add(component);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> hash.ToHashCode();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">bool</span> <span style="color:#66d9ef">operator</span> ==(ValueObject? a, ValueObject? b) =&gt; Equals(a, b);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">bool</span> <span style="color:#66d9ef">operator</span> !=(ValueObject? a, ValueObject? b) =&gt; !Equals(a, b);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> IEnumerable&lt;<span style="color:#66d9ef">object?</span>&gt; Components() =&gt;
</span></span><span style="display:flex;"><span>        Properties().SelectMany(p =&gt; Flatten(p.GetValue(<span style="color:#66d9ef">this</span>)));
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Collections count item by item, in order. The markers keep nesting distinct.</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">static</span> IEnumerable&lt;<span style="color:#66d9ef">object?</span>&gt; Flatten(<span style="color:#66d9ef">object?</span> <span style="color:#66d9ef">value</span>) =&gt;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">value</span> <span style="color:#66d9ef">is</span> IEnumerable items and not <span style="color:#66d9ef">string</span>
</span></span><span style="display:flex;"><span>            ? items.Cast&lt;<span style="color:#66d9ef">object?</span>&gt;().SelectMany(Flatten).Prepend(Start).Append(End)
</span></span><span style="display:flex;"><span>            : [<span style="color:#66d9ef">value</span>];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> PropertyInfo[] Properties()
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (Cache.TryGetValue(GetType(), <span style="color:#66d9ef">out</span> <span style="color:#66d9ef">var</span> cached))
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> cached;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Call GetProperties directly on GetType() so the trimmer can follow it</span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> found = GetType()
</span></span><span style="display:flex;"><span>            .GetProperties(BindingFlags.Instance | BindingFlags.Public)
</span></span><span style="display:flex;"><span>            .Where(p =&gt; p.GetIndexParameters().Length == <span style="color:#ae81ff">0</span>
</span></span><span style="display:flex;"><span>                &amp;&amp; !p.IsDefined(<span style="color:#66d9ef">typeof</span>(NotPartOfValueAttribute)))
</span></span><span style="display:flex;"><span>            .ToArray();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> Cache.GetOrAdd(GetType(), found);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>A value object that uses it only has to validate and expose its properties:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">ShippingRestriction</span> : ValueObject
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> ShippingRestriction(<span style="color:#66d9ef">string</span> hazardClass, <span style="color:#66d9ef">params</span> <span style="color:#66d9ef">string</span>[] bannedModes)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        ArgumentException.ThrowIfNullOrWhiteSpace(hazardClass);
</span></span><span style="display:flex;"><span>        HazardClass = hazardClass;
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Copy and sort, so callers can&#39;t mutate it and input order doesn&#39;t matter</span>
</span></span><span style="display:flex;"><span>        BannedModes = Array.AsReadOnly(
</span></span><span style="display:flex;"><span>            bannedModes.Distinct().Order(StringComparer.Ordinal).ToArray());
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">string</span> HazardClass { <span style="color:#66d9ef">get</span>; }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> IReadOnlyList&lt;<span style="color:#66d9ef">string</span>&gt; BannedModes { <span style="color:#66d9ef">get</span>; }
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">    [NotPartOfValue]</span> <span style="color:#75715e">// derived from BannedModes</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">bool</span> CanShipByAir =&gt; !BannedModes.Contains(<span style="color:#e6db74">&#34;Air&#34;</span>);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Two restrictions with the same hazard class and banned modes are equal, however the modes were passed in. Mark computed properties with <code>[NotPartOfValue]</code>. Otherwise equality evaluates them, and one that returns a new instance of its own type can recurse until the stack overflows. Sets and dictionaries don&rsquo;t promise an order, so the base class can&rsquo;t reliably compare properties of those types as written. It also allocates on every comparison, which a simple record avoids.</p>
<p>The <code>DynamicallyAccessedMembers</code> attribute is easy to leave out because everything works without it in an ordinary build. When I removed it and published a trimmed test build, values that differed compared as equal, because the trimmer had removed properties that nothing else read. It couldn&rsquo;t tell which properties the reflection call needed. The warning is IL2075 when you call <code>GetType().GetProperties()</code> directly, or IL2070 when the <code>Type</code> arrives as a parameter, such as in a cache&rsquo;s factory lambda. The attribute tells it what to keep, and the direct call lets it verify that. Test your own trimmed build, and see <a href="https://learn.microsoft.com/en-us/dotnet/core/deploying/trimming/prepare-libraries-for-trimming">Microsoft&rsquo;s trimming guidance</a> for other cases.[<a href="#references">6</a>]</p>
<h2 id="aggregates">Aggregates</h2>
<p><strong>An aggregate is a cluster of objects treated as one consistency boundary, which protects one or more invariants and is changed only through a single root entity.</strong></p>
<p>An invariant is a rule that must be true every time a transaction commits. &ldquo;Reserved stock never exceeds stock on hand&rdquo; is one. The aggregate exists to make that rule impossible to break. &ldquo;These objects are related&rdquo; is not a reason to make an aggregate. Nearly everything in a business is related to everything else.</p>
<h3 id="a-root-that-enforces-its-rule">A Root That Enforces Its Rule</h3>
<p>In the Inventory context, <code>StockItem</code> is the root. Reservations live inside it because the rule can&rsquo;t be checked without them.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">readonly</span> <span style="color:#66d9ef">record</span> <span style="color:#a6e22e">struct</span> ReservationId(Guid Value);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">record</span> <span style="color:#a6e22e">Reservation</span>(ReservationId Id, Quantity Quantity);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IDomainEvent</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">record</span> <span style="color:#a6e22e">StockReserved</span>(Sku Sku, ReservationId ReservationId, Quantity Quantity)
</span></span><span style="display:flex;"><span>    : IDomainEvent;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">DomainException</span>(<span style="color:#66d9ef">string</span> message) : Exception(message);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">InsufficientStockException</span>(Sku sku)
</span></span><span style="display:flex;"><span>    : DomainException(<span style="color:#e6db74">$&#34;Not enough available stock for {sku.Value}.&#34;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// The aggregate root. Invariant: Reserved never exceeds OnHand.</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">StockItem</span>(Sku sku, Quantity onHand)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> List&lt;Reservation&gt; _reservations = [];
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> List&lt;IDomainEvent&gt; _events = [];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> Sku Sku { <span style="color:#66d9ef">get</span>; } = sku;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> Quantity OnHand { <span style="color:#66d9ef">get</span>; <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">set</span>; } = onHand;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">int</span> Version { <span style="color:#66d9ef">get</span>; <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">set</span>; } <span style="color:#75715e">// optimistic concurrency token</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> Quantity Reserved =&gt;
</span></span><span style="display:flex;"><span>        _reservations.Aggregate(<span style="color:#66d9ef">new</span> Quantity(<span style="color:#ae81ff">0</span>), (sum, r) =&gt; sum + r.Quantity);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> Quantity Available =&gt; OnHand - Reserved;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> IReadOnlyList&lt;Reservation&gt; Reservations =&gt; _reservations.AsReadOnly();
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> IReadOnlyList&lt;IDomainEvent&gt; Events =&gt; _events.AsReadOnly();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> Reserve(ReservationId id, Quantity quantity)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        ArgumentOutOfRangeException.ThrowIfZero(quantity.Value);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        Reservation? existing = _reservations.Find(r =&gt; r.Id == id);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (existing <span style="color:#66d9ef">is</span> not <span style="color:#66d9ef">null</span>)
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">if</span> (existing.Quantity != quantity)
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> DomainException(<span style="color:#e6db74">&#34;That reservation exists with a different quantity.&#34;</span>);
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span>; <span style="color:#75715e">// the same request again changes nothing</span>
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (quantity &gt; Available)
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> InsufficientStockException(Sku);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        _reservations.Add(<span style="color:#66d9ef">new</span> Reservation(id, quantity));
</span></span><span style="display:flex;"><span>        _events.Add(<span style="color:#66d9ef">new</span> StockReserved(Sku, id, quantity));
</span></span><span style="display:flex;"><span>        Version++;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> Release(ReservationId id)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (_reservations.RemoveAll(r =&gt; r.Id == id) &gt; <span style="color:#ae81ff">0</span>)
</span></span><span style="display:flex;"><span>            Version++;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> Dispatch(ReservationId id)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        Reservation reservation = _reservations.Find(r =&gt; r.Id == id)
</span></span><span style="display:flex;"><span>            ?? <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> DomainException(<span style="color:#e6db74">&#34;No open reservation to dispatch.&#34;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        _reservations.Remove(reservation);
</span></span><span style="display:flex;"><span>        OnHand -= reservation.Quantity;
</span></span><span style="display:flex;"><span>        Version++;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> WriteOff(Quantity damaged)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (damaged &gt; Available)
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> DomainException(<span style="color:#e6db74">&#34;Release reservations before writing off that much stock.&#34;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        OnHand -= damaged;
</span></span><span style="display:flex;"><span>        Version++;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> ClearEvents() =&gt; _events.Clear();
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Outside code can read the reservations but can&rsquo;t add one. <code>AsReadOnly()</code> matters, because returning the <code>List&lt;T&gt;</code> typed as <code>IReadOnlyList&lt;T&gt;</code> lets a caller cast it back and mutate it. <code>OnHand</code> has a private setter. Every path that changes state goes through a method that keeps the rule.</p>
<p>In memory, that&rsquo;s enough. With a database, two requests can each load the same item, each see five available, and each reserve five. <code>Version</code> closes that gap, provided your persistence layer treats it as a concurrency token (<code>IsConcurrencyToken()</code> in EF Core), so the second save fails and has to retry against fresh data. It lives on the root and changes with every modification, including changes that only touch child rows. An ORM also needs mapping configuration for these types, which I&rsquo;ve left out.</p>
<h3 id="the-rules-of-thumb">The Rules of Thumb</h3>
<p>Evans&rsquo; book establishes the root as the only member that outside objects may hold on to, and requires invariants inside the boundary to hold when each transaction completes. Vaughn Vernon&rsquo;s 2011 essays, &ldquo;Effective Aggregate Design,&rdquo; sharpened this into guidance that many of us now repeat without credit, particularly keeping aggregates small and referencing other aggregates by identity.[<a href="#references">7</a>]</p>
<ul>
<li><strong>Go through the root.</strong> Don&rsquo;t hand out mutable internals, and don&rsquo;t update a child table directly. A <code>DbSet&lt;Reservation&gt;</code> that application code can write to is a hole in the wall.</li>
<li><strong>Treat the aggregate as the transaction boundary.</strong> The default is to modify one aggregate instance per transaction.</li>
<li><strong>Reference other aggregates by ID.</strong> An order line holds a <code>Sku</code>, not a <code>StockItem</code>. If you can&rsquo;t navigate to it, you&rsquo;re much less likely to modify it by accident.</li>
<li><strong>Keep them small.</strong> Include what the invariant needs and little else. <code>StockItem</code> holds open reservations only. Dispatched ones leave, and their history belongs elsewhere.</li>
<li><strong>Use eventual consistency across aggregates.</strong> If a rule spanning two of them can lag by seconds or hours, let it. Evans&rsquo; book already allows for this; Vernon made it much more prominent.</li>
</ul>
<p>Vernon also discusses reasons to break these defaults. To choose between immediate and eventual consistency, he passes along a test that came out of a discussion with Evans. Is making the data consistent the job of the user performing this action? If so, lean transactional. If it&rsquo;s another user&rsquo;s job, or the system&rsquo;s, eventual consistency is probably acceptable. Confirm it with a domain expert, because &ldquo;how stale can this be?&rdquo; is a business question.</p>
<h3 id="when-the-boundary-is-wrong">When the Boundary Is Wrong</h3>
<p>The classic mistake is modeling aggregates after the object graph. A customer has orders, orders have lines, lines have products, so <code>Customer</code> becomes the root of everything. It mirrors the foreign keys and protects nothing in particular. Symptoms worth looking for:</p>
<ul>
<li><strong>Contention.</strong> Unrelated users get concurrency conflicts or lock waits because their changes land on the same root. Changing a delivery note shouldn&rsquo;t collide with placing a new order.</li>
<li><strong>Slow loads.</strong> A one-field change pulls in thousands of child rows, or lazy loading fires query after query.</li>
<li><strong>Transactions that save several aggregates.</strong> If this is routine, either the boundary is wrong or you&rsquo;re demanding immediate consistency the business doesn&rsquo;t need.</li>
<li><strong>Collections that grow forever.</strong> Order history is a query. It rarely needs to be part of a consistency boundary.</li>
<li><strong>No invariant you can name.</strong> If you can&rsquo;t finish the sentence &ldquo;this aggregate guarantees that&hellip;&rdquo;, ask why it&rsquo;s an aggregate. A single entity with no children can be a perfectly good one, but a large cluster with no rule is not.</li>
</ul>
<p>A large aggregate is occasionally right, when a rule really does span all of it. A very popular stock item can also be a hotspot despite a correct, small boundary. Then you need to ask whether the business can tolerate occasional overselling and a way to compensate for it.</p>
<h3 id="domain-events">Domain Events</h3>
<p><strong>A domain event is a record of something that happened in the domain that other parts of the system may need to react to.</strong></p>
<p>Domain events aren&rsquo;t one of the building blocks in the 2003 book. Evans&rsquo; later <em>DDD Reference</em> lists them as a term introduced since then.[<a href="#references">1</a>] They&rsquo;re now the usual way to carry a change from one aggregate to the next. Name them in the past tense and in the domain&rsquo;s words, like <code>StockReserved</code>, not <code>StockItemRowUpdated</code>.</p>
<p>Say the Ordering context announces that a line was placed. Inventory reacts in its own transaction. A message that crosses contexts like this is often called an integration event, and it&rsquo;s a published contract, so it carries primitives instead of either model&rsquo;s types.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IStockItemRepository</span>
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    Task&lt;StockItem?&gt; FindAsync(Sku sku, CancellationToken cancellationToken);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">void</span> Add(StockItem item);
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IUnitOfWork</span>
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    Task SaveChangesAsync(CancellationToken cancellationToken);
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IOutbox</span>
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">void</span> Add(<span style="color:#66d9ef">object</span> message); <span style="color:#75715e">// stored in the same transaction as the aggregate</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">record</span> <span style="color:#a6e22e">OrderLinePlaced</span>(Guid OrderId, Guid LineId, <span style="color:#66d9ef">string</span> Sku, <span style="color:#66d9ef">int</span> Quantity);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">record</span> <span style="color:#a6e22e">StockShortfall</span>(Guid OrderId, Guid LineId);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">ReserveStockWhenOrderLinePlaced</span>(
</span></span><span style="display:flex;"><span>    IStockItemRepository stockItems, IOutbox outbox, IUnitOfWork unitOfWork)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> Task HandleAsync(OrderLinePlaced message, CancellationToken cancellationToken)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> sku = <span style="color:#66d9ef">new</span> Sku(message.Sku);
</span></span><span style="display:flex;"><span>        StockItem item = <span style="color:#66d9ef">await</span> stockItems.FindAsync(sku, cancellationToken)
</span></span><span style="display:flex;"><span>            ?? <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> DomainException(<span style="color:#e6db74">$&#34;No stock item for {sku.Value}.&#34;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">try</span>
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            item.Reserve(<span style="color:#66d9ef">new</span> ReservationId(message.LineId), <span style="color:#66d9ef">new</span> Quantity(message.Quantity));
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">catch</span> (InsufficientStockException)
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            outbox.Add(<span style="color:#66d9ef">new</span> StockShortfall(message.OrderId, message.LineId));
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">await</span> unitOfWork.SaveChangesAsync(cancellationToken);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>A shortfall isn&rsquo;t a rollback of the order, which has already committed. It&rsquo;s a business event that needs a business answer, such as a backorder or a refund.</p>
<p>Eventual consistency is work you&rsquo;re signing up for. Messages get redelivered, so handlers must tolerate repeats. Using the line ID as the reservation ID covers that while the reservation is open, but a duplicate arriving after dispatch would reserve again, so you&rsquo;d still want a record of processed messages. Events also need to survive a crash between saving and publishing, which is what the outbox is for. In this example, the infrastructure would also need to write the aggregate&rsquo;s <code>Events</code> to the outbox during the save and then clear them.</p>
<h2 id="repositories">Repositories</h2>
<p><strong>A repository gives the application the illusion of a collection of whole aggregates, hiding how they&rsquo;re stored.</strong></p>
<p>There&rsquo;s one per aggregate root that needs to be retrieved, not one per table. <code>IStockItemRepository</code> above returns a complete <code>StockItem</code> with its reservations. There&rsquo;s no <code>IReservationRepository</code>, because loading or saving a reservation on its own would bypass the rule the root exists to protect.</p>
<p>Repositories also aren&rsquo;t the place for every read. A dashboard doesn&rsquo;t need to rebuild aggregates, so give it a query that returns exactly the shape it needs. I&rsquo;ve written about <a href="/posts/repository-pattern-ef-core-specifications/">what makes a repository worth having</a> with EF Core.</p>
<h2 id="the-anemic-domain-model">The Anemic Domain Model</h2>
<p><strong>An anemic domain model has objects that carry data but little behavior, with the rules living in services that manipulate them.</strong></p>
<p>Martin Fowler named it as an anti-pattern in 2003.[<a href="#references">8</a>] It tends to look like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#75715e">// In some service, hoping every other service does the same check</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">int</span> reserved = item.Reservations.Sum(r =&gt; r.Quantity);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">if</span> (item.OnHand - reserved &gt;= quantity)
</span></span><span style="display:flex;"><span>    item.Reservations.Add(<span style="color:#66d9ef">new</span> ReservationRow { Quantity = quantity });
</span></span></code></pre></div><p>Here the classes have domain names and public setters, and the invariant is a convention. The second caller that forgets the check is your bug. The fix is the <code>Reserve</code> method above.</p>
<p>This doesn&rsquo;t mean all logic belongs in entities. Application services coordinate work (load, call, save), some domain operations don&rsquo;t naturally belong to any one object, and a CRUD screen with no rules has nothing to put in a rich model. The problem is paying for a domain model and then keeping the domain somewhere else.</p>
<h2 id="common-misunderstandings">Common Misunderstandings</h2>
<table>
  <thead>
      <tr>
          <th>You may hear this</th>
          <th>A more accurate version</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>&ldquo;Each bounded context is a microservice.&rdquo;</td>
          <td>A context bounds a model. Deployment is a separate decision.</td>
      </tr>
      <tr>
          <td>&ldquo;Ubiquitous language means one company glossary.&rdquo;</td>
          <td>The language is consistent within a context, not across all of them.</td>
      </tr>
      <tr>
          <td>&ldquo;An aggregate is a group of related objects.&rdquo;</td>
          <td>It&rsquo;s a consistency boundary around an invariant.</td>
      </tr>
      <tr>
          <td>&ldquo;The aggregate root is the parent table.&rdquo;</td>
          <td>It&rsquo;s the only entry point for changing what&rsquo;s inside the boundary.</td>
      </tr>
      <tr>
          <td>&ldquo;Every table gets a repository.&rdquo;</td>
          <td>Repositories are per aggregate root.</td>
      </tr>
      <tr>
          <td>&ldquo;An adapter is an anticorruption layer.&rdquo;</td>
          <td>Only if it translates the foreign model into yours.</td>
      </tr>
      <tr>
          <td>&ldquo;We use DDD; we have entities and repositories.&rdquo;</td>
          <td>Without language and boundaries, you have the patterns&rsquo; names.</td>
      </tr>
      <tr>
          <td>&ldquo;DDD should apply to the whole system.&rdquo;</td>
          <td>Spend the effort on the core domain.</td>
      </tr>
  </tbody>
</table>
<h2 id="where-to-start-this-week">Where to Start This Week</h2>
<ol>
<li><strong>Pick one overloaded word</strong> in your codebase (<code>Customer</code>, <code>Order</code>, <code>Product</code>, <code>Account</code>). Ask people from two departments to define it, and note where the answers diverge. If those conversations are hard to get or hard to run, Jimmy Nilsson&rsquo;s <a href="https://jimmynilsson.com/posts/tips-for-developers-on-improving-collaboration-with-domain-experts/">tips for collaborating with domain experts</a> are a practical place to begin.[<a href="#references">9</a>]</li>
<li><strong>Draw the context map you actually have</strong>, including legacy systems and third parties. Mark who can force a change on whom.</li>
<li><strong>Describe your core domain</strong> in one sentence. Compare it with where your most careful design work has gone.</li>
<li><strong>Choose one aggregate and write down its invariant.</strong> Then search for every place that changes its data without going through the root. The DDD Crew&rsquo;s <a href="https://github.com/ddd-crew/aggregate-design-canvas">Aggregate Design Canvas</a> is one tool for thinking through invariants, concurrency conflicts, and size.[<a href="#references">10</a>]</li>
<li><strong>Check your transactions.</strong> List the use cases that save more than one aggregate, and ask a domain expert how quickly each rule really needs to be true.</li>
<li><strong>Replace one primitive</strong> that has rules attached, such as a SKU or a money amount, with a value object.</li>
<li><strong>Rename one class or method</strong> to the words the business uses.</li>
</ol>
<p>None of these requires a rewrite or permission to &ldquo;do DDD.&rdquo;</p>
<h2 id="would-your-domain-expert-recognize-it">Would Your Domain Expert Recognize It?</h2>
<p>Show a domain expert the class and method names from your core domain, without the method bodies. <code>StockItem.Reserve</code>, <code>Release</code>, <code>Dispatch</code>, and <code>WriteOff</code> should start a conversation about their work. They might tell you that nobody says &ldquo;dispatch,&rdquo; or that a write-off needs approval. That&rsquo;s the model getting better.</p>
<p>If what they see is <code>ProductManager.UpdateData</code> and <code>OrderHelper.ProcessStatus</code>, the business is somewhere else, probably in the heads of whoever has been around longest. A domain expert should be able to recognize their business in your class and method names. It won&rsquo;t prove the design is right, but failing that test is a good reason to look closer.</p>
<h2 id="references">References</h2>
<ol>
<li>Eric Evans, <em>Domain-Driven Design: Tackling Complexity in the Heart of Software</em>, Addison-Wesley. His free <a href="https://domainlanguage.com/wp-content/uploads/2016/05/DDD_Reference_2015-03.pdf">Domain-Driven Design Reference</a> (2015) summarizes the patterns and marks the terms introduced since the book.</li>
<li>Jan Stenberg, <a href="https://www.infoq.com/news/2019/06/bounded-context-eric-evans">Defining Bounded Contexts: Eric Evans at DDD Europe</a>, <em>InfoQ</em>, June 26, 2019.</li>
<li>Vaughn Vernon, <em>Implementing Domain-Driven Design</em>, Addison-Wesley, 2013.</li>
<li>Microsoft. <a href="https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/implement-value-objects">Implement value objects</a>, <em>Microsoft Learn</em>, 2022.</li>
<li>Vladimir Khorikov, <a href="https://enterprisecraftsmanship.com/posts/csharp-records-value-objects/">C# 9 Records as DDD Value Objects</a>, <em>Enterprise Craftsmanship</em>, November 24, 2020.</li>
<li>Microsoft. <a href="https://learn.microsoft.com/en-us/dotnet/core/deploying/trimming/prepare-libraries-for-trimming">Prepare .NET libraries for trimming</a>, <em>Microsoft Learn</em>, 2025.</li>
<li>Vaughn Vernon, &ldquo;Effective Aggregate Design,&rdquo; 2011: <a href="https://dddcommunity.org/wp-content/uploads/files/pdf_articles/Vernon_2011_1.pdf">Part I</a>, <a href="https://www.dddcommunity.org/wp-content/uploads/files/pdf_articles/Vernon_2011_2.pdf">Part II</a>, and <a href="https://www.dddcommunity.org/wp-content/uploads/files/pdf_articles/Vernon_2011_3.pdf">Part III</a>.</li>
<li>Martin Fowler, <a href="https://martinfowler.com/bliki/AnemicDomainModel.html">AnemicDomainModel</a>, November 25, 2003.</li>
<li>Jimmy Nilsson, <a href="https://jimmynilsson.com/posts/tips-for-developers-on-improving-collaboration-with-domain-experts/">Tips for developers on improving collaboration with domain experts</a>, April 22, 2026.</li>
<li>DDD Crew, <a href="https://github.com/ddd-crew/aggregate-design-canvas">Aggregate Design Canvas</a>, <em>GitHub</em>.</li>
</ol>
]]></content:encoded></item></channel></rss>