<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aman Toumaj on Medium]]></title>
        <description><![CDATA[Stories by Aman Toumaj on Medium]]></description>
        <link>https://medium.com/@aman.toumaj?source=rss-c93d326732df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Hx1WfBBzFHYE5xh-KdK1lQ.jpeg</url>
            <title>Stories by Aman Toumaj on Medium</title>
            <link>https://medium.com/@aman.toumaj?source=rss-c93d326732df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 12:01:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aman.toumaj/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[When “Is-A” Lies: A Practical Deep Dive into LSP in Modern .NET]]></title>
            <link>https://blog.stackademic.com/when-is-a-lies-a-practical-deep-dive-into-lsp-in-modern-net-ecf1d6b230d1?source=rss-c93d326732df------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecf1d6b230d1</guid>
            <category><![CDATA[interface-segregation]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[liskov-substitution]]></category>
            <category><![CDATA[software-architect]]></category>
            <dc:creator><![CDATA[Aman Toumaj]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 14:10:26 GMT</pubDate>
            <atom:updated>2026-10-12T01:34:13.381Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll go beyond the textbook definitions and perform a <strong>tactical deep dive</strong> into <strong>LSP</strong> using <strong>C#</strong> and <strong>.NET</strong> examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ikJApFu_-5Di29upGnmKA.jpeg" /></figure><h3>Introduction</h3><p>Software developers often learn the <strong>Liskov Substitution Principle (LSP)</strong> through simple examples involving birds, penguins, rectangles, and squares. While these examples are useful for introducing the concept, they rarely explain why <strong>LSP violations</strong> become <strong>expensive architectural problems </strong>in real-world .NET applications.</p><p>The <strong>Liskov Substitution Principle</strong>, introduced by <strong>Barbara Liskov</strong> in 1987, states that derived types must be substitutable for their base types without altering the correctness of a program. In practice, this means that inheritance is not merely about sharing code. A derived class must preserve the behavioral expectations established by its parent.</p><p>In this article, we’ll go beyond the textbook definitions and perform a <strong>tactical deep dive</strong> into <strong>LSP</strong> using C# and .NET examples. We’ll examine classic violations such as the famous Penguin problem, explore more realistic business scenarios like electric charging docks, identify warning signs in production code, and discuss practical alternatives such as composition, interfaces, and domain-driven design.</p><p>By the end, you’ll be able to recognize subtle <strong>LSP violations</strong> before they evolve into <strong>fragile inheritance hierarchies</strong> and <strong>difficult-to-maintain</strong> systems.</p><h3>Why Another Article About LSP?</h3><p>If you have spent any time preparing for software engineering interviews, reading clean code books, or discussing object-oriented design, you have probably encountered the SOLID principles. Among them, the <strong>Liskov Substitution Principle</strong>, often shortened to <strong>LSP</strong>, is one of the most frequently repeated and least deeply understood principles.</p><p>Most explanations start with the same familiar examples: birds that cannot fly, squares that do not behave like rectangles, or animals that refuse to perform some expected action. These examples are useful as introductions, but they often leave developers with a shallow understanding of the principle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HjXZ06haKgB4wE09SQKugg.jpeg" /><figcaption>In real-world .NET applications, LSP violations rarely appear as obvious as a Penguin throwing an exception from a Fly() method</figcaption></figure><p>In real-world .NET applications, LSP violations rarely appear as obvious as a Penguin throwing an exception from a Fly() method. They usually appear in more subtle forms:</p><pre>public override void Save()<br>{<br>    throw new NotSupportedException();<br>}</pre><p>Or:</p><pre>if (paymentProvider is LegacyPaymentProvider)<br>{<br>    // Special handling because this provider behaves differently<br>}</pre><p>At first, these decisions may look harmless. A method is required by the base class, so the derived class overrides it. A special case is needed, so we add an if statement. A behavior does not apply, so we throw a NotSupportedException.</p><p>But over time, these small compromises accumulate. The codebase becomes fragile. New implementations become risky. Unit tests start depending on concrete types instead of abstractions. <strong>Developers lose confidence in polymorphism because the base type no longer tells the truth about what its derived types can actually do</strong>. That is where LSP becomes much more than an interview topic. It becomes a practical design tool.</p><h4>LSP Is Not Just a SOLID Checkbox</h4><p>A common mistake is treating the Liskov Substitution Principle as a theoretical rule that only matters when discussing object-oriented design in abstract terms. Many developers can recite a simplified version of the principle:</p><blockquote>A derived class should be substitutable for its base class.</blockquote><p>That definition is correct, but it is not enough. The real value of LSP appears when we ask a deeper question:</p><blockquote>Can the caller use the base type without knowing which derived type it received?</blockquote><p>This question is extremely important in .NET because so much of the ecosystem relies on abstraction and polymorphism. We use interfaces, abstract classes, dependency injection, generic constraints, mocking frameworks, pipelines, middleware, repositories, providers, handlers, and services.</p><p>For example, when we write this:</p><pre>public class OrderService<br>{<br>    private readonly IPaymentProcessor _paymentProcessor;<br><br>    public OrderService(IPaymentProcessor paymentProcessor)<br>    {<br>        _paymentProcessor = paymentProcessor;<br>    }<br><br>    public async Task PlaceOrderAsync(Order order)<br>    {<br>        await _paymentProcessor.ProcessAsync(order.TotalAmount);<br>    }<br>}</pre><p>The OrderService trusts the abstraction. It should not care whether the implementation is: <strong>StripePaymentProcessor</strong>, <strong>PayPalPaymentProcessor</strong>, <strong>BankTransferPaymentProcessor</strong>, <strong>FakePaymentProcessor </strong>or any other type of payment implementation. As long as each implementation honors the contract of IPaymentProcessor, the system remains flexible.</p><p>But if one implementation behaves unexpectedly, the abstraction becomes unreliable. For example:</p><pre>public class BankTransferPaymentProcessor : IPaymentProcessor<br>{<br>    public Task ProcessAsync(decimal amount)<br>    {<br>        if (amount &lt; 100)<br>        {<br>            throw new InvalidOperationException(<br>                &quot;Bank transfers are only supported for amounts greater than 100.&quot;);<br>        }<br><br>        return Task.CompletedTask;<br>    }<br>}</pre><p>At first glance, this may seem reasonable from a business perspective. But from the caller’s perspective, the contract has changed. However, the business rule itself is not the problem. A bank transfer provider may genuinely require a minimum transaction amount. The real design question is whether this rule is part of the expected contract of IPaymentProcessor The interface says:</p><pre>ProcessAsync(decimal amount)</pre><p>But the implementation silently adds a stronger precondition:</p><pre>amount must be greater than or equal to 100</pre><p>This is where LSP becomes practical. It forces us to ask whether our abstractions are honest. If an implementation cannot behave according to the expectations of the abstraction, then either the abstraction is wrong, the implementation belongs somewhere else, or the design needs to express that behavior more explicitly.</p><h4>Important Correction</h4><p>In the example above a bank transfer may genuinely require a minimum amount. The real LSP question is not “should this validation exist?”, but <strong>where and how should this constraint be expressed so the abstraction remains honest and predictable?</strong></p><p>The following implementation is not automatically bad:</p><pre>public class BankTransferPaymentProcessor : IPaymentProcessor<br>{<br>    public Task ProcessAsync(decimal amount)<br>    {<br>        if (amount &lt; 100)<br>        {<br>            throw new InvalidOperationException(<br>                &quot;Bank transfers are only supported for amounts greater than 100.&quot;);<br>        }<br><br>        return Task.CompletedTask;<br>    }<br>}</pre><p>The possible design problem is this:</p><pre>public interface IPaymentProcessor<br>{<br>    Task ProcessAsync(decimal amount);<br>}</pre><p>If the interface promises that <strong>every processor can process</strong> any <strong>positive amount</strong>, then BankTransferPaymentProcessor violates that expectation by introducing a stronger precondition.</p><p>This interface does not tell the caller that some payment processors may reject certain amounts because of provider-specific rules. So the real issue is not the validation. The issue is that the <strong>abstraction hides an important business constraint</strong>.</p><h3>Senior Developer Approach</h3><p>There are several good solutions depending on the domain.</p><h4>First <strong>Approach: </strong>Make Validation Part of the Contract</h4><p>If every payment processor is allowed to reject unsupported payments, then the interface should say so clearly.</p><p>Instead of only this:</p><pre>public interface IPaymentProcessor<br>{<br>    Task ProcessAsync(decimal amount);<br>}</pre><p>Use a richer request model and expose validation:</p><pre>public sealed record PaymentRequest(<br>    decimal Amount,<br>    string Currency,<br>    string CustomerId);<br><br>public sealed record PaymentValidationResult(<br>    bool IsValid,<br>    string? ErrorMessage)<br>{<br>    public static PaymentValidationResult Success()<br>        =&gt; new(true, null);<br><br>    public static PaymentValidationResult Failure(string errorMessage)<br>        =&gt; new(false, errorMessage);<br>}<br><br>public interface IPaymentProcessor<br>{<br>    PaymentValidationResult Validate(PaymentRequest request);<br><br>    Task ProcessAsync(PaymentRequest request);<br>}</pre><p>Now the BankTransferPaymentProcessor can honestly express its rules:</p><pre>public class BankTransferPaymentProcessor : IPaymentProcessor<br>{<br>    public PaymentValidationResult Validate(PaymentRequest request)<br>    {<br>        if (request.Amount &lt; 100)<br>        {<br>            return PaymentValidationResult.Failure(<br>                &quot;Bank transfers require a minimum amount of 100.&quot;);<br>        }<br><br>        return PaymentValidationResult.Success();<br>    }<br><br>    public Task ProcessAsync(PaymentRequest request)<br>    {<br>        var validationResult = Validate(request);<br><br>        if (!validationResult.IsValid)<br>        {<br>            throw new InvalidOperationException(validationResult.ErrorMessage);<br>        }<br><br>        // Execute bank transfer<br>        return Task.CompletedTask;<br>    }<br>}</pre><p>The calling code can now handle validation before processing:</p><pre>public class CheckoutService<br>{<br>    private readonly IPaymentProcessor _paymentProcessor;<br><br>    public CheckoutService(IPaymentProcessor paymentProcessor)<br>    {<br>        _paymentProcessor = paymentProcessor;<br>    }<br><br>    public async Task CheckoutAsync(PaymentRequest request)<br>    {<br>        var validationResult = _paymentProcessor.Validate(request);<br><br>        if (!validationResult.IsValid)<br>        {<br>            throw new InvalidOperationException(validationResult.ErrorMessage);<br>        }<br><br>        await _paymentProcessor.ProcessAsync(request);<br>    }<br>}</pre><p>This design does not remove the business rule. It makes the business rule discoverable. The caller no longer assumes that every processor accepts every amount. Instead, the abstraction communicates:</p><blockquote>A payment processor can validate whether a payment request is supported before processing it. This is much more LSP-friendly.</blockquote><h4>Second Approach: Use a Result Object Instead of Throwing for Business Validation</h4><p>Throwing exceptions for expected business rules is often not ideal. A minimum payment amount is not really an exceptional system failure. It is a known business condition.</p><p>So instead of this:</p><pre>throw new InvalidOperationException(&quot;Bank transfers require a minimum amount of 100.&quot;);</pre><p>You can return a result:</p><pre>public sealed record PaymentResult(<br>    bool IsSuccess,<br>    string? ErrorMessage)<br>{<br>    public static PaymentResult Success()<br>        =&gt; new(true, null);<br><br>    public static PaymentResult Failure(string errorMessage)<br>        =&gt; new(false, errorMessage);<br>}</pre><p>Then define the interface like this:</p><pre>public interface IPaymentProcessor<br>{<br>    Task&lt;PaymentResult&gt; ProcessAsync(PaymentRequest request);<br>}</pre><p>Implementation:</p><pre>public class BankTransferPaymentProcessor : IPaymentProcessor<br>{<br>    public Task&lt;PaymentResult&gt; ProcessAsync(PaymentRequest request)<br>    {<br>        if (request.Amount &lt; 100)<br>        {<br>            return Task.FromResult(<br>                PaymentResult.Failure(<br>                    &quot;Bank transfers require a minimum amount of 100.&quot;));<br>        }<br><br>        // Execute bank transfer<br>        return Task.FromResult(PaymentResult.Success());<br>    }<br>}</pre><p>Caller:</p><pre>public class CheckoutService<br>{<br>    private readonly IPaymentProcessor _paymentProcessor;<br><br>    public CheckoutService(IPaymentProcessor paymentProcessor)<br>    {<br>        _paymentProcessor = paymentProcessor;<br>    }<br><br>    public async Task CheckoutAsync(PaymentRequest request)<br>    {<br>        var result = await _paymentProcessor.ProcessAsync(request);<br><br>        if (!result.IsSuccess)<br>        {<br>            Console.WriteLine(result.ErrorMessage);<br>            return;<br>        }<br><br>        Console.WriteLine(&quot;Payment completed successfully.&quot;);<br>    }<br>}</pre><p>Now every implementation follows the same contract:</p><pre>Task&lt;PaymentResult&gt; ProcessAsync(PaymentRequest request);</pre><p>The contract does not say:</p><blockquote>Every payment will always succeed.</blockquote><p>It says:</p><blockquote>Every processor will attempt to process the payment and return a result.</blockquote><p>That is a much more <strong>honest abstraction</strong>.</p><h4>Third Approach: Use Domain Rules Outside the Processor</h4><p>Sometimes the payment processor should only execute payment, while domain validation belongs somewhere else.</p><p>For example:</p><pre>public interface IPaymentRule<br>{<br>    PaymentValidationResult Validate(PaymentRequest request);<br>}</pre><p>Bank transfer rule:</p><pre>public class BankTransferMinimumAmountRule : IPaymentRule<br>{<br>    public PaymentValidationResult Validate(PaymentRequest request)<br>    {<br>        if (request.Amount &lt; 100)<br>        {<br>            return PaymentValidationResult.Failure(<br>                &quot;Bank transfers require a minimum amount of 100.&quot;);<br>        }<br><br>        return PaymentValidationResult.Success();<br>    }<br>}</pre><p>Processor:</p><pre>public class BankTransferPaymentProcessor : IPaymentProcessor<br>{<br>    public Task&lt;PaymentResult&gt; ProcessAsync(PaymentRequest request)<br>    {<br>        // Execute payment only<br>        return Task.FromResult(PaymentResult.Success());<br>    }<br>}</pre><p>Application service:</p><pre>public class PaymentService<br>{<br>    private readonly IEnumerable&lt;IPaymentRule&gt; _rules;<br>    private readonly IPaymentProcessor _processor;<br><br>    public PaymentService(<br>        IEnumerable&lt;IPaymentRule&gt; rules,<br>        IPaymentProcessor processor)<br>    {<br>        _rules = rules;<br>        _processor = processor;<br>    }<br><br>    public async Task&lt;PaymentResult&gt; PayAsync(PaymentRequest request)<br>    {<br>        foreach (var rule in _rules)<br>        {<br>            var validationResult = rule.Validate(request);<br><br>            if (!validationResult.IsValid)<br>            {<br>                return PaymentResult.Failure(validationResult.ErrorMessage!);<br>            }<br>        }<br><br>        return await _processor.ProcessAsync(request);<br>    }<br>}</pre><p>This approach is useful when validation rules are complex, configurable, or shared across multiple flows. It also keeps the processor focused on execution rather than decision-making.</p><h3>Was the Original Example Really an LSP Violation?</h3><p>The honest answer is:</p><h4>It depends on the contract</h4><p>If IPaymentProcessor means:</p><pre>Process any positive payment amount successfully.</pre><p>Then this implementation violates LSP:</p><pre>if (amount &lt; 100)<br>{<br>    throw new InvalidOperationException();<br>}</pre><p>Because the derived implementation introduces a stronger precondition. But if IPaymentProcessor means:</p><pre>Attempt to process a payment request and return or throw a meaningful <br>result when the request is not supported.</pre><p>Then the implementation is acceptable. The problem is that the original interface is too vague.</p><pre>public interface IPaymentProcessor<br>{<br>    Task ProcessAsync(decimal amount);<br>}</pre><p>It hides too much. A better abstraction should communicate what can happen:</p><pre>public interface IPaymentProcessor<br>{<br>    Task&lt;PaymentResult&gt; ProcessAsync(PaymentRequest request);<br>}</pre><p>Or:</p><pre>public interface IPaymentMethod<br>{<br>    bool CanProcess(PaymentRequest request);<br><br>    Task&lt;PaymentResult&gt; ProcessAsync(PaymentRequest request);<br>}</pre><h4>The real senior-level lesson is:</h4><p><strong>LSP </strong>is not about ignoring valid business constraints. It is about designing abstractions that make those constraints explicit, predictable, and safe for callers.</p><blockquote>A <strong>bad abstraction</strong> hides restrictions. A <strong>good abstraction</strong> models them.</blockquote><p>A provider-specific validation rule is not automatically an LSP violation. The potential LSP issue appears when the abstraction does not communicate that such restrictions exist.</p><p>If IPaymentProcessor.ProcessAsync(decimal amount) implies that every processor can process every positive amount, then BankTransferPaymentProcessor breaks the caller’s expectations by introducing a stronger precondition.</p><p>A better design is to make the contract explicit. The abstraction can expose a validation method, return a PaymentResult, or provide a CanProcess method so the caller can discover whether a payment request is supported before attempting execution. <strong>LSP</strong> does not tell us to remove business rules. It tells us to <strong>avoid hiding business rules behind abstractions </strong>that promise more than their implementations can safely deliver.</p><h3>LSP Directly Impacts Maintainability</h3><p>Maintainability is not only about writing clean methods, meaningful names, or small classes. It is also about whether developers can safely extend the system without breaking existing behavior.</p><p><strong>LSP violations damage maintainability because they break trust.</strong></p><p>When a base class or interface says, “Every implementation can do this,” but some implementations cannot, developers are forced to defend against the abstraction, as shown in the following code example:</p><pre>if (processor is BankTransferPaymentProcessor)<br>{<br>    // Special case<br>}<br>else<br>{<br>    await processor.ProcessAsync(amount);<br>}</pre><p>This is a<strong> warning sign</strong>. The moment client code needs to inspect the concrete type, polymorphism has started to fail. Over time, this leads to several problems.</p><p>First, the <strong>code becomes harder to reason</strong> about. Instead of understanding the behavior through the abstraction, developers must know the quirks of every implementation.</p><p>Second, <strong>new implementations become dangerous</strong>. Every new subclass or interface implementation may require changes in multiple places. The <strong>Open/Closed Principle also starts to suffer</strong> because the system is no longer open for extension without modification.</p><p>Third, <strong>testing becomes more complicated</strong>. If different implementations of the same abstraction behave inconsistently, test suites must include special cases for each implementation. Instead of testing the contract once, developers are forced to test exceptions to the contract repeatedly.</p><p>Fourth, <strong>bugs become harder to detect</strong>. LSP violations often compile successfully. The compiler sees a valid override or interface implementation. The runtime behavior is where the problem appears.</p><p>That is what makes <strong>LSP violations</strong> dangerous. They are usually not syntax errors. <strong>They</strong> <strong>are design errors</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xiZIvajul7VYyP6woQU5OQ.jpeg" /><figcaption>Visual explanation of how Liskov Substitution Principle (LSP) violations break trust in software architecture. It illustrates four main consequences: making code harder to reason about, introducing dangerous new implementations, complicating testing, and causing hidden runtime bugs.</figcaption></figure><h3>The Problem Usually Starts with “Is-A”</h3><p>Many LSP violations begin with a seemingly innocent modeling decision:</p><blockquote>A penguin is a bird.</blockquote><p>That statement is true in the real world. But software design is not biology. In software, inheritance is not just about classification. It is about behavior.</p><p>If the base class Bird defines a Fly() method, then every Bird must be safely flyable from the caller’s perspective.</p><pre>public abstract class Bird<br>{<br>    public abstract void Fly();<br>}</pre><p>This works for an eagle:</p><pre>public class Eagle : Bird<br>{<br>    public override void Fly()<br>    {<br>        Console.WriteLine(&quot;The eagle is flying.&quot;);<br>    }<br>}</pre><p>But it fails for a penguin:</p><pre>public class Penguin : Bird<br>{<br>    public override void Fly()<br>    {<br>        throw new NotSupportedException(&quot;Penguins cannot fly.&quot;);<br>    }<br>}</pre><p>The issue is not that the code fails to compile. The issue is that the model lies. The base class promises that all birds can fly. The derived class breaks that promise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kWxLISPt13yEMR3vZk8FIQ.jpeg" /><figcaption>Visual explanation of how a derived class can break the promises made by its base class, using the classic “Flying Penguin” scenario to illustrate a violation of the Liskov Substitution Principle. The model creates a false expectation that all birds can fly, which fails when a penguin is introduced.</figcaption></figure><p>A better model separates identity from capability:</p><pre>public abstract class Bird<br>{<br>    public abstract void Move();<br>}<br><br>public interface IFlyable<br>{<br>    void Fly();<br>}<br><br>public class Eagle : Bird, IFlyable<br>{<br>    public override void Move()<br>    {<br>        Console.WriteLine(&quot;The eagle moves.&quot;);<br>    }<br><br>    public void Fly()<br>    {<br>        Console.WriteLine(&quot;The eagle is flying.&quot;);<br>    }<br>}<br><br>public class Penguin : Bird<br>{<br>    public override void Move()<br>    {<br>        Console.WriteLine(&quot;The penguin waddles.&quot;);<br>    }<br>}</pre><p>Now the design is more honest. A <strong>penguin is still a bird</strong>, but <strong>it is not forced into a behavior it cannot support</strong>. The system no longer needs fake implementations, runtime exceptions, or defensive type checks.</p><p>This is the core lesson:</p><blockquote><strong>Inheritance </strong>should <strong>model reliable behavioral substitution</strong>, not just real-world classification.</blockquote><h3>Real-World .NET Systems Have the Same Problem</h3><p>The bird and penguin example is simple, but the same design problem appears regularly in enterprise .NET applications. It is often hidden behind abstractions that initially look reasonable and work perfectly for the first implementation.</p><p>Consider a document storage abstraction:</p><pre>public abstract class DocumentStorage<br>{<br>    public abstract Task SaveAsync(Document document);<br>    public abstract Task&lt;Document&gt; ReadAsync(Guid documentId);<br>    public abstract Task DeleteAsync(Guid documentId);<br>}</pre><p>At first glance, this base class appears well designed. It identifies three common document operations:</p><ul><li>Saving a document</li><li>Reading a document</li><li>Deleting a document</li></ul><p>The first implementation may be backed by a relational database:</p><pre>public class SqlDocumentStorage : DocumentStorage<br>{<br>    public override Task SaveAsync(Document document)<br>    {<br>        // Save document to SQL database<br>        return Task.CompletedTask;<br>    }<br><br>    public override Task&lt;Document&gt; ReadAsync(Guid documentId)<br>    {<br>        // Read document from SQL database<br>        return Task.FromResult(new Document());<br>    }<br><br>    public override Task DeleteAsync(Guid documentId)<br>    {<br>        // Delete document from SQL database<br>        return Task.CompletedTask;<br>    }<br>}</pre><p>SqlDocumentStorage supports all operations defined by the base class, so everything appears correct. A service can depend on DocumentStorage and use it without knowing that SQL is the underlying technology:</p><pre>public sealed class DocumentService<br>{<br>    private readonly DocumentStorage _storage;<br><br>    public DocumentService(DocumentStorage storage)<br>    {<br>        _storage = storage;<br>    }<br><br>    public async Task ReplaceAsync(<br>        Guid existingDocumentId,<br>        Document replacement)<br>    {<br>        await _storage.DeleteAsync(existingDocumentId);<br>        await _storage.SaveAsync(replacement);<br>    }<br>}</pre><p>The service trusts the abstraction. It assumes that every DocumentStorage can delete an existing document and save its replacement.</p><p>As long as SqlDocumentStorage is the only implementation, that assumption remains invisible. The weakness in the abstraction becomes apparent only when the system grows.</p><h4>Introducing Immutable Audit Storage</h4><p>Suppose the application must now store documents in an immutable audit archive. The archive is append-only because audit records must not be modified or deleted after they have been written. A developer might attempt to reuse the existing hierarchy:</p><pre>public sealed class AuditDocumentStorage : DocumentStorage<br>{<br>    public override Task SaveAsync(Document document)<br>    {<br>        // Append the document to the immutable audit archive.<br>        return Task.CompletedTask;<br>    }<br><br>    public override Task&lt;Document&gt; ReadAsync(Guid documentId)<br>    {<br>        throw new NotSupportedException(<br>            &quot;Audit storage does not support reading documents.&quot;);<br>    }<br><br>    public override Task DeleteAsync(Guid documentId)<br>    {<br>        throw new NotSupportedException(<br>            &quot;Audit documents cannot be deleted.&quot;);<br>    }<br>}</pre><p>This code compiles. AuditDocumentStorage is technically a valid subclass of DocumentStorage, and the dependency injection container can inject it wherever DocumentStorage is required. Behaviorally, however, it is not a valid substitute.</p><p>The base class communicates that every document storage implementation supports saving, reading, and deleting. AuditDocumentStorage supports only saving. Its inherited type says one thing while its runtime behavior says another.</p><p>Passing it to DocumentService would break the service:</p><pre>DocumentStorage storage = new AuditDocumentStorage();<br>var service = new DocumentService(storage);<br><br>await service.ReplaceAsync(documentId, replacement);</pre><p>The caller works entirely with the base type. It does not access implementation-specific functionality or perform an invalid cast. Nevertheless, the operation fails because the derived class cannot honor the behavioral expectations established by the base class. This is a direct violation of the Liskov Substitution Principle.</p><h4>The Business Rule Is Not the Problem</h4><p>It is important to distinguish between an invalid business rule and an invalid abstraction.</p><p>Preventing the deletion of audit records may be a legitimate and essential business requirement. Removing that restriction merely to make the subclass compatible would be incorrect and potentially dangerous.</p><p>The problem is not this rule:</p><blockquote>Audit records cannot be deleted.</blockquote><p>The problem is that AuditDocumentStorage inherits from an abstraction that promises deletion. The same reasoning applies to read access. An append-only destination may legitimately accept documents without exposing them through the application. That capability limitation should be represented explicitly rather than hidden behind an inherited method that always fails.</p><p>LSP does not require every component to support every possible operation. It requires a type to honor the complete contract of the abstraction it claims to implement.</p><p>If audit storage cannot support the DeleteAsync contract, it should not be presented as a fully deletable DocumentStorage.</p><h4>Why NotSupportedException Is a Warning Sign</h4><p>Throwing NotSupportedException is not always wrong. The .NET platform itself contains APIs where an operation may not be supported, particularly when the capability is intentionally defined as conditional.</p><p>However, an unconditional NotSupportedException inside an override deserves immediate attention:</p><pre>public override Task DeleteAsync(Guid documentId)<br>{<br>    throw new NotSupportedException();<br>}</pre><p>The method exists because the base type promises the operation. The derived implementation then announces that the operation can never be performed.</p><p>This often indicates one of the following design problems:</p><ol><li>The base abstraction contains too many responsibilities.</li><li>The derived class does not belong in the inheritance hierarchy.</li><li>The design confuses common identity with common capability.</li><li>Inheritance is being used primarily for code reuse.</li><li>The abstraction was designed around its first implementation.</li></ol><p>The last problem is particularly common in enterprise systems. A base class is created around the capabilities of SQL storage. Later, cloud storage, archive storage, temporary storage, or write-only event storage must be forced into the same model.</p><p>What looked like a general abstraction was actually a SQL-shaped abstraction.</p><h4>Defensive Type Checks Do Not Solve the Problem</h4><p>One possible workaround is to make the caller identify the problematic implementation:</p><pre>public async Task ReplaceAsync(<br>    Guid existingDocumentId,<br>    Document replacement)<br>{<br>    if (_storage is AuditDocumentStorage)<br>    {<br>        await _storage.SaveAsync(replacement);<br>        return;<br>    }<br><br>    await _storage.DeleteAsync(existingDocumentId);<br>    await _storage.SaveAsync(replacement);<br>}</pre><p>This avoids the exception, but it does not solve the underlying design problem.</p><p>The service now knows about a concrete storage implementation. Every new storage type with different capabilities may require another condition:</p><pre>if (_storage is AuditDocumentStorage)<br>{<br>    // Special behavior<br>}<br>else if (_storage is ReadOnlyDocumentStorage)<br>{<br>    // Different special behavior<br>}<br>else if (_storage is ExternalArchiveStorage)<br>{<br>    // Another special case<br>}</pre><p>The abstraction is no longer protecting the caller from implementation details. Polymorphism has effectively been replaced by a growing list of type checks.</p><p>This also creates a maintenance problem. Adding a new storage implementation may require modifying every service that depends on DocumentStorage. That undermines both LSP and the Open/Closed Principle.</p><h4>Refactoring Toward Capability-Based Interfaces</h4><p>A better design is to separate storage capabilities into focused interfaces:</p><pre>public interface IDocumentWriter<br>{<br>    Task SaveAsync(<br>        Document document,<br>        CancellationToken cancellationToken = default);<br>}<br><br>public interface IDocumentReader<br>{<br>    Task&lt;Document?&gt; ReadAsync(<br>        Guid documentId,<br>        CancellationToken cancellationToken = default);<br>}<br><br>public interface IDocumentDeleter<br>{<br>    Task DeleteAsync(<br>        Guid documentId,<br>        CancellationToken cancellationToken = default);<br>}</pre><p>Each interface represents a distinct behavioral contract:</p><ul><li>IDocumentWriter promises that documents can be saved.</li><li>IDocumentReader promises that documents can be retrieved.</li><li>IDocumentDeleter promises that documents can be deleted.</li></ul><p>Implementations now declare only the capabilities they genuinely support.</p><p>A SQL-backed storage provider can implement all three:</p><pre>public sealed class SqlDocumentStorage :<br>    IDocumentWriter,<br>    IDocumentReader,<br>    IDocumentDeleter<br>{<br>    public Task SaveAsync(<br>        Document document,<br>        CancellationToken cancellationToken = default)<br>    {<br>        ArgumentNullException.ThrowIfNull(document);<br><br>        // Save the document to a SQL database.<br>        return Task.CompletedTask;<br>    }<br><br>    public Task&lt;Document?&gt; ReadAsync(<br>        Guid documentId,<br>        CancellationToken cancellationToken = default)<br>    {<br>        // Read the document from a SQL database.<br>        Document? document = new Document();<br><br>        return Task.FromResult(document);<br>    }<br><br>    public Task DeleteAsync(<br>        Guid documentId,<br>        CancellationToken cancellationToken = default)<br>    {<br>        // Delete the document from a SQL database.<br>        return Task.CompletedTask;<br>    }<br>}</pre><p>The immutable audit implementation exposes only its actual capability:</p><pre>public sealed class AuditDocumentStorage : IDocumentWriter<br>{<br>    public Task SaveAsync(<br>        Document document,<br>        CancellationToken cancellationToken = default)<br>    {<br>        ArgumentNullException.ThrowIfNull(document);<br><br>        // Append the document to the immutable audit archive.<br>        return Task.CompletedTask;<br>    }<br>}</pre><p>There are no fake operations, empty methods, misleading overrides, or unconditional NotSupportedException statements. The type system now prevents invalid usage.</p><h4>Depending on the Required Capability</h4><p>Client services should request only the capabilities they actually need.</p><p>A service that archives documents needs only a writer:</p><pre>public sealed class AuditService<br>{<br>    private readonly IDocumentWriter _writer;<br><br>    public AuditService(IDocumentWriter writer)<br>    {<br>        _writer = writer;<br>    }<br><br>    public Task ArchiveAsync(<br>        Document document,<br>        CancellationToken cancellationToken = default)<br>    {<br>        return _writer.SaveAsync(document, cancellationToken);<br>    }<br>}</pre><p>Both SQL storage and audit storage can safely satisfy this dependency because both genuinely support writing:</p><pre>IDocumentWriter sqlWriter = new SqlDocumentStorage();<br>IDocumentWriter auditWriter = new AuditDocumentStorage();</pre><h4>How This Improves LSP</h4><p>After the refactoring, every implementation can fulfill the complete contract of every interface it implements.</p><p>If a method accepts IDocumentWriter, any registered writer can be substituted safely:</p><pre>public static Task StoreAsync(<br>    IDocumentWriter writer,<br>    Document document,<br>    CancellationToken cancellationToken = default)<br>{<br>    return writer.SaveAsync(document, cancellationToken);<br>}</pre><p>The method does not need to know whether it received:</p><ul><li>SqlDocumentStorage</li><li>AuditDocumentStorage</li><li>AzureBlobDocumentStorage</li><li>FileSystemDocumentStorage</li><li>An in-memory test implementation</li></ul><p>The caller depends on a narrow and reliable behavioral promise: the supplied object can save a document. That is substitutability in practice.</p><h4>The Connection to the Interface Segregation Principle</h4><p>This refactoring also demonstrates how SOLID principles reinforce one another.</p><p>The original DocumentStorage abstraction forces every implementation to depend on all three operations. Splitting it into smaller capability-based interfaces applies the <strong>Interface Segregation Principle</strong>, or ISP:</p><blockquote>Clients should not be forced to depend on methods they do not use.</blockquote><p>At the same time, the smaller interfaces make it easier to satisfy LSP because each implementation makes fewer, more precise promises.</p><p>This is an important architectural insight:</p><blockquote>Broad abstractions are easy to violate. Focused abstractions are easier to implement honestly.</blockquote><p>LSP evaluates whether implementations preserve a contract. ISP helps us create contracts that are small enough to preserve reliably.</p><h4>Testing Becomes More Meaningful</h4><p>Focused contracts also improve automated testing. A reusable contract test can verify that every IDocumentWriter honors the same basic expectations:</p><pre>public abstract class DocumentWriterContractTests<br>{<br>    protected abstract IDocumentWriter CreateWriter();<br><br>    [Fact]<br>    public async Task SaveAsync_WithValidDocument_CompletesSuccessfully()<br>    {<br>        var writer = CreateWriter();<br>        var document = new Document();<br><br>        await writer.SaveAsync(document);<br>    }</pre><p>The same tests can be applied to every writer implementation. These are not merely implementation tests. They verify that each type preserves the behavioral contract of IDocumentWriter.</p><h4>A Practical Design Lesson</h4><p>The original DocumentStorage abstraction was not necessarily careless. It may have been entirely adequate when SQL storage was the only requirement. The problem appeared when the system evolved.</p><p>That is typical of LSP violations in enterprise software. They often begin with a reasonable abstraction designed around current requirements. As new implementations are introduced, developers discover that the supposedly universal operations were actually capabilities of the original implementation.</p><p>The correct response is not to force new implementations into the old hierarchy. It is to revisit the abstraction and express the capabilities more accurately.</p><p>The central question should be:</p><blockquote>What behavior can every implementation genuinely guarantee?</blockquote><p>Only that behavior belongs in the shared contract. Reading, writing, deletion, versioning, archiving, encryption, and search may all relate to document storage, but that does not mean every storage provider supports all of them.</p><h4>Key Takeaway</h4><p>The document storage example demonstrates why LSP is more than an academic rule about inheritance. It affects dependency injection, service design, testing, extensibility, and runtime reliability.</p><p>An abstraction should not describe everything that one implementation can do. It should describe what every implementation claiming that abstraction can reliably guarantee.</p><p>When a subtype must disable inherited operations, return meaningless values, or throw NotSupportedException unconditionally, the model is probably making promises that the subtype cannot keep.</p><h3>Final Thought</h3><p>The <strong>Liskov Substitution Principle</strong> is ultimately about creating abstractions that callers can trust. A subtype should preserve the behavioral promises of its base type without introducing unexpected restrictions, disabling supported operations, or requiring special handling based on its concrete type. As the penguin, payment method, electric vehicle, and document storage examples demonstrate, valid real-world classifications and business rules do not always translate into valid inheritance relationships. Rather than removing legitimate constraints, we should make them explicit through focused interfaces, capability-based modeling, meaningful result types, composition, and clearly defined contracts. In modern .NET development, inheritance should therefore be chosen not simply because one type <em>is a</em> another type, but because every derived implementation can safely and predictably replace its abstraction without surprising the caller.</p><p><strong>Thank you for following along with this Article! If you found this helpful, feel free to share it with your fellow developers. Happy coding!</strong></p><p><strong>Before you go</strong></p><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecf1d6b230d1" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/when-is-a-lies-a-practical-deep-dive-into-lsp-in-modern-net-ecf1d6b230d1">When “Is-A” Lies: A Practical Deep Dive into LSP in Modern .NET</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aspect-Oriented Programming (AOP) in .NET: Benefits, Pitfalls, and Best Practices]]></title>
            <link>https://medium.com/@aman.toumaj/aspect-oriented-programming-aop-in-net-benefits-pitfalls-and-best-practices-aa1d32541906?source=rss-c93d326732df------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa1d32541906</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[aspect-oriented]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[aop]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Aman Toumaj]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 15:13:19 GMT</pubDate>
            <atom:updated>2026-08-12T07:42:59.242Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical guide to using <strong>Aspect-Oriented Programming</strong> to design cleaner, more flexible, and more maintainable <strong>.NET</strong> applications.</p><figure><img alt="Like a rally team, Object-Oriented Programming keeps the application on the road, while Aspect-Oriented Programming provides guidance at the right moment by handling repetitive concerns outside the main business logic, like a co-driver supports a driver by managing guidance, warnings, and direction while the driver stays focused on the road ahead." src="https://cdn-images-1.medium.com/max/1024/1*Dg1FljIt-j1TUgUvIttsJQ.png" /><figcaption>Like a rally team, Object-Oriented Programming keeps the application on the road, while Aspect-Oriented Programming provides guidance at the right moment by handling repetitive concerns outside the main business logic, like a co-driver supports a driver by managing guidance, warnings, and direction while the driver stays focused on the road ahead.</figcaption></figure><h3>Introduction</h3><p>In modern software projects, features such as <strong>logging</strong>, <strong>validation</strong>, <strong>caching</strong>, <strong>security</strong>, <strong>transactions</strong>, and <strong>monitoring </strong>often appear repeatedly across many services and methods. <strong>Aspect-Oriented Programming</strong>, or AOP, helps manage these concerns in a cleaner way by moving them out of the business code and into reusable, centralized components. In this article, we will explore what AOP is, which problems it solves, when it should and should not be used, and how it can be applied effectively in .NET without making the system harder to understand.</p><blockquote><strong>Aspect-Oriented Programming</strong> does not replace <strong>Object-Oriented Programming</strong>. Instead, it complements it. A useful analogy is a rally team: the driver focuses on controlling the car, while the co-driver reads the route, warns about upcoming turns, and provides guidance at the right time. In the same way, <strong>object-oriented code should focus on business behavior,</strong> while aspects can handle supporting concerns such as logging, validation, transactions, caching, and monitoring. When both work together properly, the system becomes cleaner, more focused, and easier to maintain.</blockquote><h3><strong>What Is Aspect-Oriented Programming?</strong></h3><p>Aspect-Oriented Programming (AOP) is a programming paradigm that aims to separate cross-cutting concerns from the core business logic of an application. A cross-cutting concern is functionality that affects multiple parts of an application but is not part of the application’s primary business purpose. Examples include: Logging — Authentication — Authorization — Caching — Transaction management — Exception handling</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G52oGUK3bq_NuWMbtW-Pyw.png" /><figcaption>A cross-cutting concern is functionality that affects multiple parts of an application but is not part of the application’s primary business purpose.</figcaption></figure><blockquote>Without <strong>AOP</strong>, developers often repeat the same code in multiple classes and methods. AOP allows these concerns to be defined once and applied automatically where needed.</blockquote><p><strong>Example</strong></p><p>Without AOP:</p><pre>public async Task&lt;decimal&gt; CalculateCustomerPayableTaxAsync(int customerId, decimal income)<br>{<br>    _logger.LogInformation(&quot;Starting tax calculation for customer {CustomerId}&quot;, customerId);<br><br>    try<br>    {<br>        if (customerId &lt;= 0)<br>            throw new ArgumentException(&quot;Customer id must be greater than zero.&quot;);<br><br>        if (income &lt; 0)<br>            throw new ArgumentException(&quot;Income cannot be negative.&quot;);<br><br>        var customer = await _customerRepository.GetAsync(customerId);<br><br>        if (customer == null)<br>            throw new CustomerNotFoundException(customerId);<br><br>        var taxRate = customer.Country == &quot;DE&quot; ? 0.30m : 0.25m;<br>        var discount = customer.IsPremium ? 0.05m : 0m;<br>        var payableTax = income * (taxRate - discount);<br><br>        _logger.LogInformation(&quot;Tax calculated for customer {CustomerId}: {Tax}&quot;, customerId, payableTax);<br><br>        return payableTax;<br>    }<br>    catch (Exception ex)<br>    {<br>        _logger.LogError(ex, &quot;Tax calculation failed for customer {CustomerId}&quot;, customerId);<br>        throw;<br>    }<br>}</pre><p>With<strong> AOP</strong>, <strong>logging</strong>, <strong>input validation</strong> and <strong>error handling</strong> can be implemented separately and automatically executed before and after the business method. The following method contains <strong>pure business logic</strong>, <strong>without any cross-cutting concerns</strong>. It has only <strong>one single responsibility</strong>: to calculate the customer’s tax. It is much easier to write a focused unit test without having to worry about other aspects such as logging, caching, or error handling. It is much easier to read, debug and extend.</p><pre>[LogExecution]<br>[ValidateInput]<br>[HandleException]<br>public async Task&lt;decimal&gt; CalculateCustomerPayableTaxAsync(int customerId, decimal income)<br>{<br>    var customer = await _customerRepository.GetAsync(customerId);<br><br>    if (customer == null)<br>        throw new CustomerNotFoundException(customerId);<br><br>    var taxRate = customer.Country == &quot;DE&quot; ? 0.30m : 0.25m;<br>    var discount = customer.IsPremium ? 0.05m : 0m;<br><br>    return income * (taxRate - discount);<br>}</pre><h3>Core AOP Concepts</h3><p>Before examining AOP implementations in .NET, it is important to understand a few core terms. These concepts explain how AOP separates <strong>cross-cutting concerns</strong> from <strong>business logic</strong> and how additional behavior can be applied without directly modifying the original method.</p><h4>Aspect</h4><p>An <strong>aspect</strong> is a reusable module that contains a cross-cutting concern. In simple terms, an aspect is the place where we put logic that is needed in many parts of the application but does not belong to the main business logic. Common examples include: LoggingAspect — CachingAspect — ValidationAspect — TransactionAspect — AuthorizationAspect</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-eWBuuH7y7r3ey6lvqJXg.png" /><figcaption>An <strong>aspect</strong> is a reusable module that contains a cross-cutting concern</figcaption></figure><p>For example, logging is usually not the main responsibility of a business method. A method named CalculateCustomerPayableTaxAsync should focus on calculating tax, not on writing logs before and after execution.</p><p>Example: Logging Aspect</p><pre>public class LoggingAspect<br>{<br>    private readonly ILogger&lt;LoggingAspect&gt; _logger;<br><br>    public LoggingAspect(ILogger&lt;LoggingAspect&gt; logger)<br>    {<br>        _logger = logger;<br>    }<br><br>    public async Task&lt;T&gt; ExecuteAsync&lt;T&gt;(<br>        string methodName,<br>        Func&lt;Task&lt;T&gt;&gt; action)<br>    {<br>        _logger.LogInformation(&quot;Executing method {MethodName}&quot;, methodName);<br><br>        var result = await action();<br><br>        _logger.LogInformation(&quot;Method {MethodName} executed successfully&quot;, methodName);<br><br>        return result;<br>    }<br>}</pre><p>The aspect contains the logging behavior. The business method does not need to know how logging is implemented.</p><p>A method can then stay focused:</p><pre>[LoggingAspect]<br>public async Task&lt;decimal&gt; CalculateCustomerPayableTaxAsync(int customerId, decimal income)<br>{<br>    var customer = await _customerRepository.GetAsync(customerId);<br>    var taxRate = customer.Country == &quot;DE&quot; ? 0.30m : 0.25m;<br>    var discount = customer.IsPremium ? 0.05m : 0m;<br>    return income * (taxRate - discount);<br>}</pre><p>The key idea is that the aspect handles a repeated technical concern, while the method keeps its business responsibility.</p><h4>Join Point</h4><p>A <strong>join point</strong> is a specific point during program execution where an aspect can be applied. Typical join points include: —<strong> Method execution</strong> — <strong>Method call</strong> — <strong>Property access </strong>—<strong> Object construction</strong> — <strong>Exception throwing</strong></p><p>In .NET applications, the most common join point is usually <strong>method execution</strong>, especially when using interceptors, decorators, filters, or dynamic proxies.</p><h4>Example: Method Execution as a Join Point</h4><p>Consider this method:</p><pre>public async Task&lt;decimal&gt; CalculateCustomerPayableTaxAsync(int customerId, decimal income)<br>{<br>    // Business logic<br>}</pre><p>The execution of this method is a join point. An aspect can run:</p><ul><li><strong>Before </strong>this method starts</li><li><strong>After </strong>this method completes</li><li><strong>Around </strong>the whole method execution</li><li><strong>When </strong>this method throws an exception</li></ul><p>Example:</p><pre>Log before method<br>    → CalculateCustomerPayableTaxAsync()<br>Log after method</pre><p>In <strong>ASP.NET Core</strong>, <strong>filters </strong>also work in a similar way because filters allow code to run before or after specific stages of the request processing pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pq-3VWNbWegZISMbtJtskA.png" /><figcaption>This diagram visualizes the core concept of Aspect-Oriented Programming (AOP), illustrating how modular aspects are applied to specific, illustrative “join points” within program execution, with a particular emphasis on the .NET imperative. The panel on the far right focuses on the “.NET JOIN POINT CONTEXT,” stating that Method Execution is typically the most common join point in .NET applications.</figcaption></figure><h4>Advice</h4><p>Advice is the action executed at a join point. If the join point is “method execution,” the advice defines what should happen before, after, around, or when an exception occurs during that method execution.</p><p>Common advice types include:</p><ul><li><strong>Before advice:</strong> Runs before the method.</li><li><strong>After advice:</strong> Runs after the method.</li><li><strong>Around advice:</strong> Wraps the method and controls execution.</li><li><strong>Exception advice:</strong> Runs when the method throws an exception.</li></ul><h4>Before Advice</h4><p>Before advice runs before the business method.</p><pre>public void Before(string methodName)<br>{<br>    _logger.LogInformation(&quot;Starting method {MethodName}&quot;, methodName);<br>}</pre><h4>After Advice</h4><p>After advice runs after the business method finishes.</p><pre>public void After(string methodName)<br>{<br>    _logger.LogInformation(&quot;Finished method {MethodName}&quot;, methodName);<br>}</pre><h4>Around Advice</h4><p>Around advice wraps the entire method execution. It is the most powerful type because it can decide whether the method should execute, modify inputs, handle the result, or catch exceptions.</p><pre>// Aspect:<br>// The aspect contains cross-cutting concerns: logging and execution-time measurement.<br>public async Task&lt;T&gt; AroundAsync&lt;T&gt;(<br>    string methodName,<br>    Func&lt;Task&lt;T&gt;&gt; action)<br>{<br>    // Advice:<br>    // This is part of the &quot;around advice&quot;.<br>    // It runs before the original business method starts.<br>    var stopwatch = Stopwatch.StartNew();<br><br>    try<br>    {<br>        // Before advice:<br>        // Runs before the join point.<br>        _logger.LogInformation(&quot;Starting {MethodName}&quot;, methodName);<br><br>        // Join point:<br>        // This is the execution of the original business method.<br>        var result = await action();<br><br>        // After advice:<br>        // Runs after the join point completes successfully.<br>        _logger.LogInformation(&quot;Completed {MethodName}&quot;, methodName);<br><br>        return result;<br>    }<br>    finally<br>    {<br>        // After advice:<br>        // Runs after the join point finishes, whether it succeeds or throws an exception.<br>        stopwatch.Stop();<br><br>        // After advice:<br>        // Logs the execution time after the original method execution.<br>        _logger.LogInformation(<br>            &quot;{MethodName} took {ElapsedMilliseconds} ms&quot;,<br>            methodName,<br>            stopwatch.ElapsedMilliseconds);<br>    }<br>}</pre><p>For example, a caching aspect may decide not to execute the method at all if the result already exists in cache. In this sample, the <strong>aspect</strong> is the caching wrapper itself, the <strong>advice</strong> is the logic that runs around the business method, and the <strong>join point</strong> is the execution of the original method represented by action().</p><pre>// Aspect: CachingAspect<br>// This reusable component contains the cross-cutting concern: caching.<br>public async Task&lt;T&gt; AroundAsync&lt;T&gt;(<br>    string cacheKey,<br>    Func&lt;Task&lt;T&gt;&gt; action) // Join point reference: represents the original business method to be executed<br>{<br>    // Advice: logic executed before the business method<br>    var cachedValue = await _cache.GetAsync&lt;T&gt;(cacheKey);<br><br>    // Advice: decision logic<br>    if (cachedValue != null)<br>        return cachedValue;<br><br>    // Join Point: execution of the original business method<br>    // This is where the actual target method runs.<br>    var result = await action();<br><br>    // Advice: logic executed after the business method<br>    await _cache.SetAsync(cacheKey, result);<br><br>    // Advice: return the final result to the caller<br>    return result;<br>}</pre><h4>Pointcut</h4><p>A <strong>pointcut</strong> defines where an aspect should be applied. If an aspect describes <strong>what</strong> should happen, the pointcut describes <strong>where</strong> it should happen. For example, a pointcut may apply logging to all methods inside the Application.Services namespace or only to methods decorated with [LogExecution].</p><p>Example:</p><pre>Apply logging to all methods inside the Application.Services namespace.</pre><p>Or:</p><pre>Apply transaction handling to all methods ending with &quot;Async&quot; inside command services.</pre><h4>Weaving</h4><p>Finally, weaving is the process of combining aspects with the business code. Depending on the framework, weaving can happen at compile time, build time, or runtime. <strong>Weaving</strong> is the process of combining aspects with the business code. In other words, weaving is how the aspect actually becomes part of the application execution flow. The exact implementation depends on the framework. Some frameworks modify code, while others use proxies, decorators, or interceptors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWZr12_E8QsWaVv8sqKeeA.png" /><figcaption>This detailed technical infographic illustrates the Aspect-Oriented Programming (AOP) concept of weaving, demonstrating how modular cross-cutting concerns, or aspects, are combined with core business code to produce a final executable application flow.</figcaption></figure><h3>Clean Coding and Single Responsibility</h3><p>The examples above also show why <strong>AOP</strong> can support <strong>clean coding</strong> and the <strong>Single Responsibility Principle</strong>. In the first version, the CalculateCustomerPayableTaxAsync method is responsible for more than one thing. It retrieves a customer, validates the inputs, writes log messages, handles exceptions, and decides how errors should be reported. <strong>Even though the method is still small, its responsibilities are already mixed.</strong></p><p>From a clean code perspective, this makes the method harder to read and maintain. <strong>Imagine a practical code example in which the lines of code within the method body can be sufficiently extensive.</strong> The actual business logic — retrieving a customer and calculating tax is surrounded by extensive infrastructure code. If logging rules change, the service method must be modified. If exception handling changes, the same method must be touched again. These are different reasons to change, which means the method is not fully aligned with the <strong>Single Responsibility Principle</strong> and furthermore <strong>violate</strong> the <strong>OCP (open for extension, closed for modification)</strong> principle of the SOLID design principles.</p><p>With AOP, logging, input validation and exception handling can be moved into separate aspects. The business method becomes focused only on its real purpose:</p><pre>var customer = await _customerRepository.GetAsync(customerId);<br><br>if (customer == null)<br>    throw new CustomerNotFoundException(customerId);<br><br>var taxRate = customer.Country == &quot;DE&quot; ? 0.30m : 0.25m;<br>var discount = customer.IsPremium ? 0.05m : 0m;<br><br>return income * (taxRate - discount);</pre><p>Conceptual Example:</p><p>Now imagine a large-scale monolithic enterprise software application with at least 500,000 to 5 Million lines of code. The illustration below might serve as a good example of a enterprise application — shown once without AOP and once with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QAlpRO73dP6gmNz0hoHRVg.png" /><figcaption>AOP helps transform tangled cross-cutting concerns into separated, reusable aspects, allowing the core business logic to remain cleaner, more focused, and easier to maintain.</figcaption></figure><p><strong>Based on search data in internet, here is the scale of monolithic codebases:</strong></p><p>. Large Monolithic Enterprise Applications ~ 1 Million to 10 Million+</p><p>. Automotive Software, for example Mercedes car ~ 50 Million</p><p>. Google Monolithic Repository (Monorepo) ~ 2 Billion</p><h3><strong>What Problems Does AOP Solve?</strong></h3><p>AOP mainly solves problems caused by <strong>cross-cutting concerns</strong>, which are behaviors that appear across many parts of an application but are not part of the core business logic.</p><h4><strong>Code Duplication</strong></h4><p>One of the most visible problems <strong>AOP </strong>solves is code duplication. In a large application, the same technical logic may appear in hundreds of places:</p><ul><li><strong>Logging in many service methods</strong></li><li><strong>Validation in many application services</strong></li><li><strong>Performance measurements around many operations</strong></li></ul><p>At first, this duplication may look harmless. A few lines of logging or validation do not seem like a serious problem. But over time, the same pattern gets copied again and again. Eventually, the application contains repeated infrastructure code scattered across many classes.</p><blockquote>AOP helps centralize this logic. Instead of writing the same logging or validation code inside every method, the concern can be defined once as an aspect and applied wherever it is needed.</blockquote><h4><strong>Improved Maintainability</strong></h4><p>Duplicated code is difficult to change. For example, imagine that the logging format changes. Without AOP, developers may need to update dozens or hundreds of methods manually. With AOP, the logging behavior can be changed in one place. The same improvement is then applied consistently across all methods that use that aspect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a82hmsZsk6lY1g9RREuz3w.png" /><figcaption>On the left, under the title “WITHOUT AOP: CHAOS,” a disorganized, messy workshop is depicted. Small engineer characters struggle with repeating, manual connections for main functions like “Calculate Tax” and “Process Order.” Duplicated logic modules for concerns such as logging, authorization, transactions, and exception handling are attached directly and repetitively to each service block. On the right, under the title “WITH AOP: ORDER,” a clean, futuristic console is shown in a vast, organized data center. A wise senior architect calmly manages a streamlined system using a central “Aspect Manager Node.”</figcaption></figure><h4><strong>Better Separation of Concerns</strong></h4><p>Business classes should primarily focus on business rules. A method named CalculateCustomerPayableTaxAsync should clearly express how customer tax is calculated. It should not be dominated by logging, exception handling, transaction management, auditing, and performance measurement. Without AOP, business logic and technical concerns often become mixed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUBD7AurlL80boB4qOxwRw.png" /><figcaption>This split-screen infographic, titled “AOP: Achieving Clean Separation of Concerns in Business Logic,” illustrates the transformative effect of Aspect-Oriented Programming on software development. The left panel, representing “BEFORE AOP,” depicts a chaotic, tangled mess of wires, pipes, and gears converging on a central processor labeled CalculateCustomerPayableTaxAsync, symbolizing how technical boilerplate—such as logging, exception handling, and auditing—overwhelms and obscures core business logic, leaving a developer stressed. The right panel, “AFTER AOP,” contrasts this by showing a clean, orderly server room environment where these extraneous technical concerns have been extracted into separate, reusable “Aspect Modules” connected externally to the main process.</figcaption></figure><h4><strong>Consistency</strong></h4><p>Another problem AOP solves is inconsistency. In real projects, different developers may implement the same concern in slightly different ways. One developer may add logging before and after a method. Another may only log exceptions. Another may forget logging completely.</p><p>AOP helps enforce consistent behavior across the application. If a method requires logging, authorization, or auditing, the corresponding aspect can apply the same rule every time. This is especially useful in enterprise applications where consistency is important for debugging, monitoring, compliance, and security.</p><h4><strong>Reduced Boilerplate</strong></h4><p>Large enterprise systems can contain thousands of lines of repetitive infrastructure code. When this pattern appears repeatedly, the codebase becomes noisy. Developers must mentally filter out the boilerplate before they can understand the real business logic. AOP reduces this noise by moving repeated technical behavior into reusable aspects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPnRwZBK98WX7U5spmvtZg.png" /><figcaption>A detailed illustration contrasts the chaos of redundant code with the order brought by Aspect-Oriented Programming (AOP). On the left, an overwhelmed developer is buried under towering stacks of folders labeled with repetitive boilerplate like “TRY LOGGER” and “TRY SECURITY,” surrounded by screens of endless code.</figcaption></figure><h3><strong>When Should AOP Be Used?</strong></h3><p>AOP is particularly useful when dealing with concerns that appear throughout many components of an application. These are usually called <strong>cross-cutting concerns</strong>, because they cut across multiple classes, services, layers, or modules instead of belonging to one specific business feature. Common examples include logging, security, transaction management, caching, error handling, and performance monitoring.</p><h4><strong>Logging</strong></h4><p>Logging is one of the most common use cases for AOP. Many methods need to log when execution starts, when execution finishes, how long execution took, and whether an exception occurred. If this logic is written manually inside every method, the business logic becomes harder to read.</p><p>Instead of this:</p><pre>public async Task&lt;decimal&gt; CalculateCustomerPayableTaxAsync(int customerId, decimal income)<br>{<br>    _logger.LogInformation(&quot;Starting tax calculation for customer {CustomerId}&quot;, customerId);<br><br>    try<br>    {<br>        var result = await CalculateTaxInternalAsync(customerId, income);<br><br>        _logger.LogInformation(&quot;Tax calculation completed for customer {CustomerId}&quot;, customerId);<br><br>        return result;<br>    }<br>    catch (Exception ex)<br>    {<br>        _logger.LogError(ex, &quot;Tax calculation failed for customer {CustomerId}&quot;, customerId);<br>        throw;<br>    }<br>}</pre><p><strong>AOP </strong>allows the method to stay focused on the actual business operation:</p><pre>[LogExecution]<br>public async Task&lt;decimal&gt; CalculateCustomerPayableTaxAsync(int customerId, decimal income)<br>{<br>    return await CalculateTaxInternalAsync(customerId, income);<br>}</pre><p>This makes logging reusable, consistent, and easier to change later.</p><h4>Authorization and Security Checks</h4><p>AOP is also useful when the same authorization or policy checks must be applied across multiple operations. Security is a typical cross-cutting concern because many parts of an application may need access control, but authorization logic should not be copy-pasted into every business method.</p><p>For example:</p><pre>[AuthorizePermission(&quot;Customer.Tax.Read&quot;)]<br>public async Task&lt;decimal&gt; CalculateCustomerPayableTaxAsync(int customerId, decimal income)<br>{<br>    // Business logic<br>}</pre><p>This is especially useful when the rule is technical or policy-based, such as checking whether the current user has permission to execute a method. However, domain-specific business rules should usually remain explicit inside the domain or application layer.</p><h4><strong>Caching</strong></h4><p>Caching can also benefit from AOP when the same caching pattern is repeated in multiple query methods. For example, reading product information, customer details, configuration values, or reference data may follow a similar cache-first strategy.</p><p>Example:</p><pre>[CacheResult(DurationInMinutes = 10)]<br>public async Task&lt;CustomerDto&gt; GetCustomerAsync(int customerId)<br>{<br>    return await _customerRepository.GetCustomerDtoAsync(customerId);<br>}</pre><h4><strong>Transaction Management</strong></h4><p>Transaction handling is another strong candidate for <strong>AOP</strong>. Many enterprise operations need the same pattern: start a transaction, execute business logic, commit when successful, and roll back when an error occurs. Transaction management is frequently described as a classic <strong>AOP </strong>use case because it often applies across many service methods.</p><p>Instead of repeating transaction code everywhere, the method can be marked declaratively:</p><pre>[Transactional]<br>public async Task CreateInvoiceAsync(CreateInvoiceCommand command)<br>{<br>    // Business logic<br>}</pre><h4>Benefits</h4><p>One of the main benefits of <strong>AOP </strong>is cleaner and more maintainable code. In real-world applications, business methods often become mixed with repetitive concerns such as logging, validation, caching, exception handling, and transaction management. This makes the code harder to read, harder to test, and more likely to contain bugs.</p><p>AOP helps by moving these cross-cutting concerns into separate, reusable components. As a result, business methods become more focused and expressive. Developers can understand the real intention of the code faster, and future changes to logging, validation, or monitoring can be made in one place instead of being repeated across the application.</p><h4>Clean Up Spaghetti Code</h4><p><strong>Cross-cutting concerns</strong> rarely become a problem overnight. They usually grow slowly. At the beginning of a project, adding a few lines of logging, validation, caching, authorization, or exception handling directly inside a method does not seem dangerous. The code works, the feature is delivered, and the duplication feels small enough to ignore.</p><p>Then the same pattern appears in another method.</p><p>And another.</p><p>And another.</p><p>Soon, the application contains the same technical logic scattered across many classes and services. What started as a harmless shortcut becomes a maintenance problem. This is similar to the <strong>well-known boiled frog metaphor</strong>.</p><blockquote>If a <strong>problem appears suddenly</strong>, we <strong>usually react immediately</strong>. But <strong>when the complexity increases slowly</strong>, one small copy-paste at a time, <strong>we may not notice the damage until the codebase has already become difficult to change.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3z5EjzY5jvISrjvpwHEEw.png" /><figcaption>Symbolizing how a codebase can become overwhelming when complexity increases slowly. Small engineer-fairies are trying to untangle and guide organized aspect threads (like AOP as the cure) into clean, restructured methods on the right, contrasted against the chaotic, “boiled frog” state on the left</figcaption></figure><h3><strong>When Should AOP Not Be Used?</strong></h3><p>AOP is not a universal solution. It is useful for separating cross-cutting concerns, but it should not be applied blindly. If AOP is used in the wrong place, it can hide important behavior, make debugging harder, and reduce the readability of the system.</p><blockquote>The <strong>goal </strong>of <strong>AOP </strong>is to make code easier to understand, not more mysterious.</blockquote><h4><strong>Business Logic</strong></h4><p>Business rules should generally remain explicit.</p><p>Bad example:</p><pre>[ApplyDiscount]<br>public decimal CalculatePrice(decimal amount)<br>{<br>  return amount;<br>}</pre><p>At first glance, this method looks simple. But the real behavior is hidden. A reader cannot easily understand how the final price is calculated! Because the discount logic is not visible inside the method.</p><p>A developer may ask:</p><ul><li>Which discount is applied?</li><li>Is it a seasonal discount?</li><li>Is it based on customer type?</li><li>Is it based on country, product category, or order amount?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KzyFvfeLrOinQ04E_mWtVQ.png" /><figcaption>A split-screen infographic contrasts two approaches to implementing business logic in software development. On the left, Aspect-Oriented Programming hides complex discount calculations behind a simple attribute, causing confusion and obscurity for the developer. On the right, making business rules explicit creates clarity, allowing the execution flow and auditable logic to be easily followed and understood.</figcaption></figure><h4><strong>Complex Hidden Behavior</strong></h4><p>Excessive AOP usage can make the execution flow difficult to follow. One of the main advantages of AOP is that it removes repetitive infrastructure code from business methods. However, if too many aspects are applied, the opposite problem can appear: the method looks clean, but the real behavior becomes hidden.</p><p>Developers may struggle to determine:</p><ul><li>Which part of the code executes first</li><li>Which aspects are active</li><li>Whether an aspect changes method parameters or return values</li><li>Whether the original method is executed at all</li><li>Why a specific behavior occurs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5OskWRKByTqGGFEuExBIQ.png" /><figcaption>An infographic titled “The Perils of Excessive AOP: Complex Hidden Behavior” illustrates the chaos of overusing Aspect-Oriented Programming. A bewildered developer is overwhelmed by a tangled web of multiple aspects layered around a central business method, creating an obscure execution flow. This visualization highlights how excessive AOP hides core logic and makes debugging a developer’s nightmare, as summarized by the concluding text box.</figcaption></figure><p>For example, consider the following method:</p><pre>[AuthorizePermission(&quot;Customer.Tax.Read&quot;)]<br>[ValidateInput]<br>[CacheResult(DurationInMinutes = 10)]<br>[Transactional]<br>[Audit(Action = &quot;CalculateTax&quot;)]<br>[LogExecution]<br>[MeasurePerformance]<br>[HandleException]<br>public async Task&lt;decimal&gt; CalculateCustomerPayableTaxAsync(int customerId, decimal income)<br>{<br>    return await _taxCalculator.CalculateAsync(customerId, income);<br>}</pre><p>At first glance, the method looks very clean. It has only one line of business code. But the actual execution flow is much more complex than it appears. This is where <strong>AOP </strong>can become <strong>dangerous</strong>. The source code looks simple, but the runtime behavior is distributed across many separate components. To understand what really happens, a developer must inspect the method, the attributes, the aspect implementations, and the aspect execution order.</p><blockquote>AOP becomes a design smell when the correctness of the application depends on hidden ordering rules that are not obvious from the method itself.</blockquote><p>A better approach is to keep aspect usage intentional and limited:</p><pre>[AuthorizePermission(&quot;Customer.Tax.Read&quot;)]<br>[ValidateInput]<br>[LogExecution]<br>public async Task&lt;decimal&gt; CalculateCustomerPayableTaxAsync(int customerId, decimal income)<br>{<br>    return await _taxCalculator.CalculateAsync(customerId, income);<br>}</pre><p>A good rule of thumb is:</p><blockquote><em>If a developer cannot understand the behavior of a method without checking five different aspects, the design may be too hidden.</em></blockquote><p><strong>AOP should reduce noise</strong>, not hide essential behavior. The goal is to make the codebase easier to maintain, not to create a second invisible execution path outside the business code.</p><h4><strong>Small Applications</strong></h4><p>For small projects, AOP may introduce more complexity than value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pySFJGeYY0P-mfiaHGthyA.png" /><figcaption>Conceptual infographic illustrating why AOP might be overkill for small applications. It shows a stark contrast between the straightforward, manageable nature of a small project and the immense overhead and confusion that an AOP framework can introduce. For small tasks, the added complexity of configuration and ‘magic’ often outweighs the value of modularizing cross-cutting concerns.</figcaption></figure><h4><strong>Critical Performance Scenarios</strong></h4><p>Some AOP mechanisms rely on reflection, dynamic proxies, or interception. These introduce overhead that may be unacceptable in high-performance systems.</p><h4><strong>Team Inexperience</strong></h4><p>If developers do not understand AOP, maintenance costs can increase significantly.</p><h3><strong>AOP in .NET</strong></h3><p>.NET does not provide a complete AOP framework out of the box, but offers several mechanisms that can implement AOP-like behavior.</p><h4><strong>Middleware</strong></h4><p>ASP.NET Core middleware is often considered a form of AOP.</p><p>Example:</p><pre>// Aspect:<br>// This whole middleware represents a Logging Aspect.<br>// It contains a cross-cutting concern: request logging.<br>app.Use(async (context, next) =&gt;<br>{<br>    // Before Advice:<br>    // This code runs before the next endpoint is executed.<br>    _logger.LogInformation(&quot;Request started&quot;);<br><br>    // Join Point:<br>    // This represents the point where the next component in the pipeline is executed.<br>    await next();<br><br>    // After Advice:<br>    // This code runs after the next middleware or endpoint has completed.<br>    _logger.LogInformation(&quot;Request completed&quot;);<br>});</pre><p>The <strong>aspect</strong> is the logging behavior implemented by this middleware.</p><h4><strong>Filters</strong></h4><p>ASP.NET Core MVC and Web API filters provide <strong>aspect-like capabilities</strong>. They allow developers to run code before or after specific stages of the request processing pipeline, without placing that code directly inside controller actions.</p><p>For example, instead of writing logging logic inside every controller action, we can create a reusable filter:</p><pre>public class LoggingFilter : ActionFilterAttribute<br>{<br>    private readonly ILogger&lt;LoggingFilter&gt; _logger;<br><br>    public LoggingFilter(ILogger&lt;LoggingFilter&gt; logger)<br>    {<br>        _logger = logger;<br>    }<br><br>    public override void OnActionExecuting(ActionExecutingContext context)<br>    {<br>        var actionName = context.ActionDescriptor.DisplayName;<br><br>        _logger.LogInformation(&quot;Executing action: {ActionName}&quot;, actionName);<br>    }<br><br>    public override void OnActionExecuted(ActionExecutedContext context)<br>    {<br>        var actionName = context.ActionDescriptor.DisplayName;<br><br>        if (context.Exception == null)<br>        {<br>            _logger.LogInformation(&quot;Action executed successfully: {ActionName}&quot;, actionName);<br>        }<br>        else<br>        {<br>            _logger.LogError(<br>                context.Exception,<br>                &quot;Action failed: {ActionName}&quot;,<br>                actionName);<br>        }<br>    }<br>}</pre><p>Then it can be applied to a controller action:</p><pre>[ServiceFilter(typeof(LoggingFilter))]<br>public async Task&lt;IActionResult&gt; GetCustomerTax(int customerId)<br>{<br>    var tax = await _taxService.CalculateCustomerPayableTaxAsync(customerId);<br><br>    return Ok(tax);<br>}</pre><p>From an AOP perspective, this can be understood like this:</p><ul><li><strong>Aspect:</strong> LoggingFilter</li><li><strong>Join point:</strong> execution of the GetCustomerTax action</li><li><strong>Before advice:</strong> OnActionExecuting</li><li><strong>After advice:</strong> OnActionExecuted</li><li><strong>Pointcut:</strong> the [ServiceFilter(typeof(LoggingFilter))] attribute that determines where the filter is applied</li></ul><p>Filters can also be registered globally, so they apply to all controllers or actions:</p><pre>builder.Services.AddControllers(options =&gt;<br>{<br>    options.Filters.Add&lt;LoggingFilter&gt;();<br>});</pre><p><strong>ASP.NET Core </strong>provides several filter types, and each one runs at a different stage of the pipeline. Microsoft documents filter types such as <strong>authorization filters</strong>, <strong>resource filters</strong>, <strong>action filters</strong>, <strong>exception filters</strong>, and <strong>result filters</strong>.</p><h4><strong>Decorator Design Pattern</strong></h4><p>Many developers prefer the <strong>Decorator Design Pattern</strong> because the additional behavior remains explicit. Unlike some AOP implementations, where behavior may be applied through attributes, proxies, or build-time weaving, decorators make the wrapping structure visible in regular object-oriented code.</p><p>A decorator implements the same interface as the original service and receives the original service as a dependency. It can then add behavior before or after delegating the call to the real implementation.</p><p>For example:</p><pre>public interface IOrderService<br>{<br>    Task CreateOrderAsync(Order order);<br>}<br><br>public class OrderService : IOrderService<br>{<br>    public async Task CreateOrderAsync(Order order)<br>    {<br>        // Core business logic for creating an order<br>    }<br>}</pre><p>A logging decorator can then wrap the original service:</p><pre>public class LoggingOrderService : IOrderService<br>{<br>    private readonly IOrderService _inner;<br>    private readonly ILogger&lt;LoggingOrderService&gt; _logger;<br><br>    public LoggingOrderService(<br>        IOrderService inner,<br>        ILogger&lt;LoggingOrderService&gt; logger)<br>    {<br>        _inner = inner;<br>        _logger = logger;<br>    }<br><br>    public async Task CreateOrderAsync(Order order)<br>    {<br>        _logger.LogInformation(&quot;Creating order&quot;);<br><br>        await _inner.CreateOrderAsync(order);<br><br>        _logger.LogInformation(&quot;Order created successfully&quot;);<br>    }<br>}</pre><p>From an AOP perspective, the decorator behaves like an aspect:</p><ul><li><strong>Aspect:</strong> LoggingOrderService</li><li><strong>Join point:</strong> CreateOrderAsync</li><li><strong>Before advice:</strong> log before calling _inner.CreateOrderAsync(order)</li><li><strong>After advice:</strong> log after the call completes</li><li><strong>Pointcut:</strong> the dependency injection registration that decides which service is wrapped</li></ul><p>The main advantage of decorators is transparency. A developer can easily see that LoggingOrderService wraps another IOrderService. This makes the execution flow easier to understand and easier to debug. However, decorators can become verbose if many cross-cutting concerns must be applied to many services.</p><h4><strong>Dynamic Proxies</strong></h4><p>Dynamic proxies provide another way to implement AOP-like behavior in .NET. Instead of manually writing decorators for every service, a proxy object is generated at runtime. This proxy intercepts method calls and allows additional behavior to run before, after, or around the original method.</p><p>Libraries such as <strong>Castle DynamicProxy</strong> are commonly used for this purpose. They can create proxy objects that intercept calls to services and delegate those calls through interceptors.</p><p><strong>Popular Libraries</strong></p><p>Examples include:</p><ul><li>Castle DynamicProxy</li><li>Autofac Interceptors</li><li>AspectInjector</li><li>PostSharp</li><li>Fody</li></ul><h3><strong>Risks and Disadvantages of Improper AOP Usage</strong></h3><p>AOP is powerful, but it comes with trade-offs. When used carefully, it improves separation of concerns and reduces duplicated code. When used without discipline, it can hide important behavior, make debugging harder, and create unexpected dependencies between parts of the system.</p><h4><strong>Hidden Dependencies</strong></h4><p>One of the biggest risks of AOP is hidden dependency. A class may appear simple because its methods contain only business logic, but in reality, the class may depend on several aspects that are applied externally.</p><p>A good rule is:</p><blockquote><em>If a method depends on an aspect for correctness, not only for technical support, that dependency should be visible and well documented.</em></blockquote><p>For example, logging can usually remain hidden because it does not change the business result. But if an aspect changes the returned value, prevents execution, modifies parameters, or applies business rules, the hidden dependency becomes dangerous.</p><h4><strong>Debugging Complexity</strong></h4><p>Debugging also becomes more difficult when execution passes through multiple aspects, interceptors, middleware components, or filters before reaching the actual business method.</p><p>Without AOP, the execution flow is usually easier to follow:</p><pre>Controller<br>    → Service<br>        → Repository</pre><p>With AOP, the real flow may look more like this:</p><pre>Controller<br>    → Authorization Aspect<br>        → Validation Aspect<br>            → Caching Aspect<br>                → Logging Aspect<br>                    → Transaction Aspect<br>                        → Business Method<br>                    → Transaction Aspect<br>                → Logging Aspect<br>            → Caching Aspect<br>        → Validation Aspect<br>    → Authorization Aspect</pre><p>This can make troubleshooting more difficult. When something goes wrong, developers may need to inspect several separate components before understanding the root cause.</p><h4><strong>Unexpected Side Effects</strong></h4><p>AOP becomes risky when aspects are not independent from each other. Ideally, <strong>each aspect</strong> should have a <strong>clear responsibility</strong> and should not rely on hidden assumptions about which aspect runs before or after it. For example, caching, logging, validation, and transaction handling may all be applied to the same method. If caching runs before validation, invalid input may be used to create a cache key. If a transaction starts before validation, the application may open unnecessary transactions for invalid requests. When the correctness of the application depends on a fragile aspect order, this is an <strong>AOP design smell.</strong></p><blockquote><strong>Aspects </strong>should be <strong>independent </strong>where possible, and when ordering is required, it should be explicit, documented, and tested.</blockquote><p>For example:</p><pre>Caching → Logging → Validation → Transaction → Business Logic</pre><p>At first glance, this may look harmless. However, if the order matters. Then if caching runs before validation, invalid input might be used to build a cache key. If a transaction starts before validation, the application may open unnecessary database transactions for requests that should have been rejected immediately.</p><p><strong>Consider the following method:</strong></p><pre>[CacheResult]<br>[LogExecution]<br>[ValidateCustomerId]<br>public async Task&lt;decimal&gt; CalculateCustomerPayableTaxAsync(int customerId)<br>{<br>    var customer = await _customerRepository.GetAsync(customerId);<br>    return customer.Income * 0.30m;<br>}</pre><p>The intention is simple:</p><ol><li>Validate the customer id.</li><li>Log the method execution.</li><li>Cache the result.</li><li>Execute the business logic only when necessary.</li></ol><p><strong>However, if the aspects are executed in the wrong order, the behavior can become incorrect.</strong></p><p>For example, imagine the CacheResult aspect runs before ValidateCustomerId:</p><pre>public class CacheResultAspect<br>{<br>    public async Task&lt;object&gt; ExecuteAsync(<br>        Func&lt;Task&lt;object&gt;&gt; next,<br>        object[] arguments)<br>    {<br>        var customerId = (int)arguments[0];<br><br>        var cacheKey = $&quot;tax:{customerId}&quot;;<br><br>        var cachedValue = await _cache.GetAsync(cacheKey);<br><br>        if (cachedValue != null)<br>            return cachedValue;<br><br>        var result = await next();<br><br>        await _cache.SetAsync(cacheKey, result);<br><br>        return result;<br>    }<br>}</pre><p>And the validation aspect looks like this:</p><pre>public class ValidateCustomerIdAspect<br>{<br>    public async Task&lt;object&gt; ExecuteAsync(<br>        Func&lt;Task&lt;object&gt;&gt; next,<br>        object[] arguments)<br>    {<br>        var customerId = (int)arguments[0];<br><br>        if (customerId &lt;= 0)<br>            throw new ArgumentException(&quot;Customer id must be greater than zero.&quot;);<br><br>        return await next();<br>    }<br>}</pre><p>If CacheResultAspect runs first, this call may create or check a cache entry using an invalid customer id:</p><pre>await taxService.CalculateCustomerPayableTaxAsync(-1);</pre><p>The better order would be:</p><pre>Validation → Logging → Caching → Business Logic</pre><p>In code, this would conceptually mean:</p><pre>[ValidateCustomerId]<br>[LogExecution]<br>[CacheResult]<br>public async Task&lt;decimal&gt; CalculateCustomerPayableTaxAsync(int customerId)<br>{<br>    var customer = await _customerRepository.GetAsync(customerId);<br>    return customer.Income * 0.30m;<br>}</pre><p>Now invalid input is rejected before logging, caching, or business execution continues.</p><p><strong>Common Design Smell</strong></p><p>The sample above is one of the common design smells in AOP: <strong>aspects become indirectly dependent on execution order</strong>. When the correctness of the application depends on a fragile aspect chain order, the system becomes harder to test, debug and maintain.</p><p><strong>A good rule is:</strong></p><blockquote>If changing the order of aspects can break the application, the design should be reviewed.</blockquote><h3><strong>AOP and SOLID Principles</strong></h3><h4><strong>Does AOP Support SOLID?</strong></h4><p>Generally yes,<strong> when used correctly</strong>. AOP can help enforce several <strong>SOLID principles </strong>by separating technical concerns from domain behavior.</p><h4><strong>AOP and the Single Responsibility Principle (SRP)</strong></h4><p>The Single Responsibility Principle states: A class should have only one reason to change.</p><p>Without AOP:</p><pre>public class OrderService<br>{<br>  public async Task CreateOrderAsync()<br>  {<br>    Validate();<br>    Log();<br>    StartTransaction();<br>    // Business logic<br>    CommitTransaction();<br>    }<br>}</pre><p>This class has multiple responsibilities: Business processing — Logging — Validation — Transaction management. Any change to these concerns requires modifying the service.</p><p>With AOP:</p><pre>public class OrderService<br>{<br>  [Log]<br>  [Validate]<br>  [Authorization]<br>  [StartTransaction]<br>  [CommitTransaction]<br>  public async Task CreateOrderAsync()<br>  {<br>    // Business logic only<br>  }<br>}</pre><p>The sample above aligns closely with SRP.</p><p><strong>The Warning: </strong>AOP can also violate SRP if aspects become overly complex.</p><p>For example:</p><pre>public class MegaAspect<br>{<br>  // Logging<br>  // Authorization<br>  // Validation<br>  // Caching<br>  // Monitoring<br>}</pre><p><strong>This simply moves the violation elsewhere. Good AOP design means that each aspect should itself have a single, well-defined responsibility.</strong></p><h3><strong>Conclusion</strong></h3><p>Aspect-Oriented Programming is a powerful <strong>architectural technique</strong> for handling <strong>cross-cutting concerns</strong> such as logging, security, caching, auditing, and transaction management. When applied appropriately, it reduces duplication, promotes cleaner code, and supports principles such as <strong>SRP </strong>and <strong>OCP</strong>.</p><p>However, <strong>AOP </strong>is not a substitute for good design. Excessive or inappropriate use can hide behavior, complicate debugging, and make systems harder to understand. Successful adoption requires careful consideration, transparency, and disciplined application.</p><p>For .NET developers, <strong>AOP </strong>should be viewed as a specialized tool: <strong>highly valuable for infrastructure concerns</strong>, but <strong>rarely the correct place for core business logic.</strong></p><h3>Final Thought</h3><blockquote><em>“Software development is not just about writing code; it’s about managing complexity. </em><strong><em>AOP provides the tools to master this complexity</em></strong><em> by focusing on the core of the business. The difference between a coder and an architect is the ability to see the ‘big picture.’ </em><strong><em>With AOP, you no longer have to struggle with cross-cutting concerns but can instead focus on business rules</em></strong>.<em>”</em></blockquote><p><strong>Thank you for following along with this Article! If you found this helpful, feel free to share it with your fellow developers. Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa1d32541906" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Robust Strategy Pattern in .NET 10: Building a Fail-Safe Tax Calculation Engine]]></title>
            <link>https://medium.com/@aman.toumaj/robust-strategy-pattern-in-net-10-building-a-fail-safe-tax-calculation-engine-5ecb3003f2dd?source=rss-c93d326732df------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ecb3003f2dd</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Aman Toumaj]]></dc:creator>
            <pubDate>Sat, 07 Feb 2026 23:31:12 GMT</pubDate>
            <atom:updated>2026-02-13T12:09:05.272Z</atom:updated>
            <content:encoded><![CDATA[<h3>Robust Strategy Pattern in .NET 10: Building a Fail-Safe Tax Calculation Engine</h3><p>Practical guide to building a flexible, testable, and fail-safe tax calculation engine using C# features. Why your next business-critical calculation engine shouldn’t rely on switch statements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OR04Nf-CMOSsctk3h297w.jpeg" /><figcaption>Decoupling Logic: Using Modular Strategies for Scalable Tax Calculation</figcaption></figure><h3>Introduction</h3><p>In modern software development, business rules are rarely static. Whether you are dealing with shipping providers, payment gateways, or — as in our case — tax calculations, the logic often depends on a specific context.</p><p>Imagine you are building a payroll system. Tax laws are notoriously volatile; they change every year, vary by region, and depend on the payment frequency (Daily, Monthly, or Yearly). A common “quick fix” is a large switch statement inside a SalaryService. It starts small, but as new tax laws emerge, that single method grows into a 1000-line &quot;God Method&quot; that is impossible to test, breaks easily, and violates the <strong>Open/Closed Principle</strong>.</p><p>In this article, we will walk through a robust solution using the <strong>Strategy Pattern</strong> in .NET, we will build a system that is not only easy to extend but also “Fail-Fast” — ensuring that if a tax rule is missing, the system stops immediately rather than calculating an incorrect salary.</p><h3>Source Code</h3><p>For those who want to dive straight into the implementation, the complete source code is available on my GitHub: <strong>→ </strong><a href="https://github.com/tomajexpress/Robust.Strategy.Design.Pattern"><strong>Download Source Code from GitHub</strong></a></p><h3>Fundamentals of the Strategy Design Pattern</h3><p>Before we dive into the implementation of our tax engine, it’s essential to understand the “Why” behind the “How.” In software engineering, the <strong>Strategy Design Pattern</strong> is one of the pillars of the behavioral patterns defined by the Gang of Four (GoF).</p><h4>What is the Strategy Design Pattern?</h4><p>At its core, the Strategy pattern is about <strong>Interchangeability</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94MS7jaA3qacj_U8txsOGw.jpeg" /><figcaption>A visual breakdown of the Strategy Design Pattern, illustrating how specific algorithms (Strategies A, B, and C) are decoupled from the business logic (Context) through a shared Interface, enabling seamless interchangeability.</figcaption></figure><p><strong>Definition:</strong> The Strategy Design Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. In a real-world application, this means you don’t hardcode “how” a calculation happens inside your business logic. Instead, your business logic (the <strong>Context</strong>) holds a reference to a contract (the <strong>Interface</strong>), and you plug in the specific math (the <strong>Strategy</strong>) at runtime.</p><h3>The Three Pillars of the Pattern</h3><p>To understand the theory, you must visualize three distinct roles:</p><ol><li><strong>The Strategy (Interface):</strong> This is the common contract for all supported algorithms. It defines the “shape” of the operation. In our project, this is ITaxCalculatorStrategy.</li><li><strong>The Concrete Strategies:</strong> These are the actual implementations of the algorithms. Each class handles one specific logic variant (e.g., MonthlyTaxCalculation). They are isolated units of logic that are easy to test and modify without affecting others.</li><li><strong>The Context (The Client):</strong> This is the class that needs the calculation. It doesn’t know <em>which</em> strategy it’s using; it only knows that the object it holds follows the Strategy Interface. In our codebase, the SalaryCalculator acts as the context.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*pUbQBBSSqQHCyme-NWxDWg.jpeg" /><figcaption>A visual breakdown of the Strategy Design Pattern. It emphasizes how behavior can vary independently at runtime without modifying the client</figcaption></figure><h4>The Core Architecture</h4><p>Instead of one monolithic class, we decompose our logic into three parts:</p><ol><li><strong>The Strategy Interface:</strong> Defining the contract.</li><li><strong>Concrete Strategies:</strong> Specific implementations (Daily, Monthly, Yearly).</li><li><strong>The Locator:</strong> A smart factory that picks the right strategy at runtime.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fj16tNdbUOhdYn7TxB5gwQ.jpeg" /><figcaption>UML Class Diagram of the Tax Calculation Engine</figcaption></figure><h3>Project Setup</h3><h4>1. Creating the Solution</h4><p>Open <strong>Visual Studio 2022</strong> (or later) and create a new <strong>Blank Solution</strong> named <strong>Robust.Strategy.Design.Pattern.</strong> To separate our infrastructure from our core logic, we will organize the solution using separate <strong>class libraries</strong> and <strong>folders</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*zKKVT7pA1zKfgYuXuqO55A.png" /><figcaption>Solution structure</figcaption></figure><h4>2. The Core Layer (StrategyDesignPattern.Core)</h4><p>In Clean Architecture, this is your most important library. It should be a <strong>Class Library</strong> project. It contains the heart of your application:</p><ul><li><strong>Interfaces:</strong> (ISalaryCalculator.cs, ITaxCalculatorStrategy) define the &quot;what&quot; without worrying about the &quot;how.&quot;</li><li><strong>Domain Logic:</strong> (SalaryCalculator.cs and the TaxCalculation folder) contains the actual business rules.</li><li><strong>Enums:</strong> Constants and types used across the logic.</li><li><strong>Configurations:</strong> The “Dependency Injection” wiring that keeps implementations internal.</li></ul><blockquote><strong><em>Clean Architecture Tip:</em></strong><em> Keep this layer free of external dependencies (like databases or specific UI frameworks). It should only depend on .NET built-in types.</em></blockquote><h4>3. The Presentation Layer (StrategyDesignPattern.ConsoleApp)</h4><p>This is your <strong>Console Application</strong> (or Web API App in other scenarios).</p><ul><li><strong>Role:</strong> It acts as the entry point for the user.</li><li><strong>Dependency:</strong> It only references StrategyDesignPattern.Core.</li><li><strong>Restriction:</strong> Because we will use the internal modifier for classes in Core, this project can only see the Interfaces and the DependencyConfigurations class. It cannot &quot;cheat&quot; by manually creating tax strategies.</li></ul><h4>4. The Testing Layer (StrategyDesignPattern.TestProject)</h4><p>This is typically an <strong>xUnit, NUnit, or MSTest Project</strong>.</p><ul><li><strong>Role:</strong> To verify that your strategies calculate taxes correctly.</li><li><strong>Dependency:</strong> It references StrategyDesignPattern.Core.</li><li><strong>Visibility:</strong> Since your implementations will be internal, you would typically add [assembly: InternalsVisibleTo(&quot;StrategyDesignPattern.TestProject&quot;)] in your Core project&#39;s .csproj to allow the test project to see the internal classes for unit testing.</li></ul><h3>Implementation of the Tax Calculation Engine</h3><h4>1. Defining the Domain: The SalaryType</h4><p>We start by defining the categories of salaries our system handles. We use an <strong>enum </strong>to represent the context of the calculation.</p><pre>namespace StrategyDesignPattern.Core.Enums;<br><br>public enum SalaryType<br>{<br>    Daily,<br>    Monthly,<br>    Yearly<br>}</pre><h4>2. The Contract: ITaxCalculatorStrategy</h4><p>The heart of the Strategy pattern is the interface. Unlike a simple calculation method, our interface includes a <strong>Satisfies </strong>method. This allows the strategy to &quot;announce&quot; whether it is the right tool for the job.</p><pre>namespace StrategyDesignPattern.Core.TaxCalculation;<br><br>public interface ITaxCalculatorStrategy<br>{<br>    decimal CalculateTax(decimal amount);<br>    bool Satisfies(SalaryType salaryType);<br>}</pre><ul><li><strong>CalculateTax:</strong> The mathematical implementation.</li><li><strong>Satisfies:</strong> The logic that determines if this strategy matches the user’s request.</li></ul><h4>3. Implementing the Strategies</h4><p>We create a class for every tax rule. This keeps our code modular. If the “Daily” tax law changes, we only touch the <strong>DailyTaxCalculation</strong> class.</p><p>Implementation of daily tax calculation:</p><pre>namespace StrategyDesignPattern.Core.TaxCalculation;<br><br>internal class DailyTaxCaculation : ITaxCalculatorStrategy<br>{<br>    public decimal CalculateTax(decimal amount)<br>    {<br>        return amount * 0.05m;<br>    }<br><br>    public bool Satisfies(SalaryType salaryType)<br>    {<br>        return salaryType == SalaryType.Daily;  <br>    }<br>}</pre><p>Implementation of monthly tax calculation:</p><pre>namespace StrategyDesignPattern.Core.TaxCalculation;<br><br>internal class MonthyTaxCaculation : ITaxCalculatorStrategy<br>{<br>    public decimal CalculateTax(decimal amount)<br>    {<br>        return amount * 0.15m;<br>    }<br><br>    public bool Satisfies(SalaryType salaryType)<br>    {<br>        return salaryType == SalaryType.Monthly;<br>    }<br>}</pre><p>Implementation of annual tax calculation:</p><pre>namespace StrategyDesignPattern.Core.TaxCalculation;<br><br>internal class YearlyTaxCaculation : ITaxCalculatorStrategy<br>{<br>    public decimal CalculateTax(decimal amount)<br>    {<br>        return amount * 0.25m;<br>    }<br><br>    public bool Satisfies(SalaryType salaryType)<br>    {<br>        return salaryType == SalaryType.Yearly;<br>    }<br>}</pre><h4>4. The Locator: Decoupling Selection from Execution</h4><p>How does the system pick the right strategy? Instead of the service doing the searching, we delegate this to a <strong>Locator</strong>. The biggest mistake that developers sometimes make with the Strategy pattern is manually instantiating classes. Instead, using .NET 10’s <strong>Primary Constructors</strong>, we inject an IEnumerable&lt;ITaxCalculator&gt;. The DI container automatically finds all registered strategies and passes them here.</p><p>Definition of the interface for the ITaxCalculatorLocator:</p><pre>namespace StrategyDesignPattern.Core.TaxCalculation;<br><br>public interface ITaxCalculatorLocator<br>{<br>    ITaxCalculatorStrategy GetTaxCalculator(SalaryType salaryType);<br>}</pre><p>Implementation of TaxCalculatorLocator:</p><pre>namespace StrategyDesignPattern.Core.TaxCalculation;<br><br>internal class TaxCalculatorLocator(IEnumerable&lt;ITaxCalculatorStrategy&gt; taxCalculators) : ITaxCalculatorLocator<br>{<br>    public ITaxCalculatorStrategy GetTaxCalculator(SalaryType salaryType)<br>    {<br>        var taxCalculator = taxCalculators.FirstOrDefault(tc =&gt; tc.Satisfies(salaryType));<br><br>        if (taxCalculator == null)<br>        {<br>            // Fail-Fast: It is better to crash than to calculate wrong taxes.<br>            throw new InvalidOperationException($&quot;No tax calculator found for the given salary type: {salaryType}&quot;);<br>        }<br><br>        return taxCalculator;<br>    }   <br>}</pre><p><strong>Why InvalidOperationException is critical in this implementation</strong></p><p>In financial applications, <strong>“Silent Failures”</strong> (such as returning 0 tax because a calculation type was unknown) are dangerous and can lead to significant fiscal errors. Throwing an InvalidOperationException ensures that any missing strategy is caught immediately during development or logged as a high-priority alert in production.</p><p>While the <strong>Result Pattern</strong> is arguably a more stable candidate — as it treats errors as <strong>“first-class citizens”</strong> and forces the developer to explicitly check result.IsSuccess before accessing a value—we have opted for <strong>Exception-based linking</strong> in this specific architecture. This decision was made to enforce a &quot;Fail-Fast&quot; boundary: if the system reaches a state where a required strategy is missing, it is treated as an exceptional configuration error that must be resolved immediately, rather than a business logic branch that the application should attempt to gracefully bypass.</p><h4>5. The Orchestrator: SalaryCalculator</h4><p>Finally, the SalaryCalculator uses the locator to get the right strategy and perform the final subtraction. Because of our architecture, this class doesn&#39;t care <em>how</em> tax is calculated; it only cares that it <em>is</em> calculated.</p><p>Definition of the interface for the ISalaryCalculator:</p><pre>namespace StrategyDesignPattern.Core;<br><br>public interface ISalaryCalculator<br>{<br>    decimal CalculateSalaryAfterTax(decimal amount, SalaryType salaryType);<br>}</pre><p>Implementation of SalaryCalculator:</p><pre>namespace StrategyDesignPattern.Core;<br><br>internal class SalaryCalculator(ITaxCalculatorLocator taxCalculatorLocator) : ISalaryCalculator<br>{<br>    private readonly ITaxCalculatorLocator _taxCalculatorLocator = taxCalculatorLocator;<br><br>    public decimal CalculateSalaryAfterTax(decimal amount, SalaryType salaryType)<br>    {<br>        var taxCalculator = _taxCalculatorLocator.GetTaxCalculator(salaryType);<br>        var tax = taxCalculator.CalculateTax(amount);<br>        return amount - tax;<br>    }<br>}</pre><h4>💡 Architectural Deep Dive: Why not use .NET Keyed Services?</h4><p>You might be wondering: <em>“Since .NET 8, we have built-in </em><strong><em>Keyed Services</em></strong><em>. Why write a custom Locator?”</em></p><p>While Keyed Services are a fantastic feature for reducing boilerplate in standard applications, I opted for a custom <strong>Locator Pattern</strong> in this Domain-Centric architecture for three specific reasons:</p><ol><li><strong>Framework Agnosticism (Pure Domain Logic):</strong> Keyed Services require the consumption of specific DI abstractions (like IKeyedServiceProvider or attributes) within your business logic. By injecting a simple IEnumerable&lt;ITaxCalculatorStrategy&gt;, our Core layer remains purely focused on C# interfaces, unaware of the specific Dependency Injection container used to wire them.</li><li><strong>Encapsulated Selection Logic:</strong> With Keyed Services, the selection logic is often tied to the registration phase (mapping an Enum to a Type). In our Locator, the selection logic is dynamic (tc.Satisfies(salaryType)). This allows the strategy <em>itself</em> to define its applicability, strictly adhering to the <strong>Open/Closed Principle</strong>. If the selection criteria become more complex than a simple Enum match later on, we can adapt the Locator without changing the client code.</li><li><strong>Explicit “Fail-Fast” Control:</strong> The custom Locator gives us a centralized place to handle missing strategies. As shown in the code above, we can throw a specific InvalidOperationException with a custom message. This ensures that a missing strategy is treated as a critical configuration error during development, rather than a silent failure or a generic container exception.</li></ol><h3>The Fortress Pattern: Encapsulation through Internal Implementations</h3><p>In a typical project, developers often make everything public, leading to &quot;leaky abstractions&quot; where the UI or API layer starts manually instantiating classes it shouldn&#39;t even know exist. In our <strong>Fail-Safe Tax Engine</strong>, we do things differently. We treat our implementation details like a black box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mXOO7Dyho4WxJbjRSPXe9Q.jpeg" /><figcaption>Encapsulation through Internal Implementations</figcaption></figure><h4>1. Hiding the “How”</h4><p>Every concrete strategy (DailyTaxCalculation, etc.) and even the TaxCalculatorLocator are marked as internal. This means that StrategyDesignPattern.ConsoleApp <strong>cannot</strong> see these classes. It cannot accidentally do new DailyTaxCalculation().</p><h4>2. The Configuration Gateway</h4><p>Since the implementations are hidden, we provide a single public entry point in the StrategyDesignPattern.Core.Configurations namespace:</p><pre>namespace StrategyDesignPattern.Core.Configurations;<br><br>public class DependencyConfigurations<br>{<br>    public static void RegisterTaxCalculation(ServiceCollection services)<br>    {<br>        // Internal classes registered as Public Interfaces<br>        services.AddSingleton&lt;ITaxCalculatorStrategy, DailyTaxCaculation&gt;();<br>        services.AddSingleton&lt;ITaxCalculatorStrategy, MonthyTaxCaculation&gt;();<br>        services.AddSingleton&lt;ITaxCalculatorStrategy, YearlyTaxCaculation&gt;();<br><br>        services.AddSingleton&lt;ITaxCalculatorLocator, TaxCalculatorLocator&gt;();<br>        services.AddSingleton&lt;ISalaryCalculator, SalaryCalculator&gt;();<br>    }<br>}</pre><h4>3. Wiring it up in Program.cs</h4><p>The Console Application only needs to know two things:</p><ol><li>The <strong>Interfaces</strong> (the “what”).</li><li>The <strong>Registration Method</strong> (the “how to start”).</li></ol><p>In your Program.cs, the setup remains clean and decoupled:</p><pre>var services = new ServiceCollection();<br><br>// 1. Register Services<br>DependencyConfigurations.RegisterTaxCaculation(services);<br><br>// 2. Build the Provider<br>using var serviceProvider = services.BuildServiceProvider();<br><br>// 3. Resolve Services<br>var salaryCalculator = serviceProvider.GetRequiredService&lt;ISalaryCalculator&gt;();<br><br>decimal grossSalary = 5000m;<br>decimal netSalary = salaryCalculator.CalculateSalaryAfterTax(grossSalary, SalaryType.Monthly);<br><br>Console.WriteLine($&quot;Gross: {grossSalary:C}&quot;);<br>Console.WriteLine($&quot;Net (Monthly Strategy): {netSalary:C}&quot;);</pre><h4>Why this matters for a Robust Engine:</h4><ul><li><strong>Zero Leakage:</strong> No one can bypass the SalaryCalculator or the Locator to use a strategy directly.</li><li><strong>Easy Refactoring:</strong> You can rename, merge, or delete internal classes within the Core project without ever breaking the Console, Web, or Mobile apps that consume it.</li><li><strong>True Decoupling:</strong> The outer layers depend purely on abstractions, which is the ultimate goal of the <strong>Dependency Inversion Principle</strong>.</li></ul><h3>Unit Testing: Ensuring 100% Coverage</h3><p>One of the greatest benefits of this pattern is its testability. To ensure our logic is bulletproof, we use <strong>MSTest</strong>, <strong>Moq</strong>, and <strong>FluentAssertions</strong>. By using <strong>Moq</strong> and <strong>FluentAssertions</strong>, we can verify the orchestration logic without running the actual math.</p><p>Salary Calculator Tests:</p><pre>namespace StrategyDesignPattern.Core.TestProject;<br><br>[TestClass]<br>public class SalaryCalculatorTests<br>{<br>    [TestMethod]<br>    public void CalculateSalaryAfterTax_ShouldReturnCorrectNetValue()<br>    {<br>        // Arrange<br>        var locatorMock = new Mock&lt;ITaxCalculatorLocator&gt;();<br>        var strategyMock = new Mock&lt;ITaxCalculator&gt;();<br>        <br>        locatorMock.Setup(l =&gt; l.GetTaxCalculator(SalaryType.Monthly))<br>                    .Returns(strategyMock.Object);<br><br>        strategyMock.Setup(s =&gt; s.CalculateTax(1000m)).Returns(150m);<br><br>        var sut = new SalaryCalculator(locatorMock.Object);<br><br>        // Act<br>        var result = sut.CalculateSalaryAfterTax(1000m, SalaryType.Monthly);<br><br>        // Assert<br>        result.Should().Be(850m); // 1000 - 150<br>    }<br>}</pre><p>Tax Calculation Strategy Tests:</p><pre>namespace StrategyDesignPattern.TestProject;<br><br>[TestClass]<br>public class TaxStrategyTests<br>{<br>    [TestMethod]<br>    [DataRow(1000, 50)] // 5% of 1000<br>    public void DailyTax_ShouldCalculateCorrectly(double amount, double expectedTax)<br>    {<br>        var sut = new DailyTaxCaculation();<br>        sut.CalculateTax((decimal)amount).Should().Be((decimal)expectedTax);<br>        sut.Satisfies(SalaryType.Daily).Should().BeTrue();<br>    }<br><br>    [TestMethod]<br>    [DataRow(1000, 150)] // 15% of 1000<br>    public void MonthlyTax_ShouldCalculateCorrectly(double amount, double expectedTax)<br>    {<br>        var sut = new MonthyTaxCaculation();<br>        sut.CalculateTax((decimal)amount).Should().Be((decimal)expectedTax);<br>        sut.Satisfies(SalaryType.Monthly).Should().BeTrue();<br>    }<br><br>    [TestMethod]<br>    [DataRow(1000, 250)] // 25% of 1000<br>    public void YearlyTax_ShouldCalculateCorrectly(double amount, double expectedTax)<br>    {<br>        var sut = new YearlyTaxCaculation();<br>        sut.CalculateTax((decimal)amount).Should().Be((decimal)expectedTax);<br>        sut.Satisfies(SalaryType.Yearly).Should().BeTrue();<br>    }<br>}</pre><p><strong>Unit Test for Strategy Coverage — Guarding the Enum:</strong> This test will automatically fail if someone adds a new SalaryType to the enum but forgets to create a calculation class for it.</p><pre>namespace StrategyDesignPattern.TestProject;<br><br>[TestClass]<br>public class TaxCalculatorLocatorTests<br>{<br>    [TestMethod]<br>    public void AllSalaryTypes_ShouldHaveAValidStrategy()<br>    {<br>        // Arrange<br>        var strategies = new List&lt;ITaxCalculatorStrategy&gt;<br>        {<br>            new DailyTaxCaculation(),<br>            new MonthyTaxCaculation(),<br>            new YearlyTaxCaculation()<br>        };<br><br>        var locator = new TaxCalculatorLocator(strategies);<br><br>        // Act &amp; Assert<br>        foreach (SalaryType type in Enum.GetValues(typeof(SalaryType)))<br>        {<br>            Action act = () =&gt; locator.GetTaxCalculator(type);<br>            act.Should().NotThrow&lt;InvalidOperationException&gt;(<br>                $&quot;because the enum value {type} must have a registered strategy.&quot;);<br>        }<br>    }<br>}</pre><blockquote><em>We have also written more unit tests. Those interested can check out the source code on my GitHub: </em><strong><em>→ </em></strong><a href="https://github.com/tomajexpress/Robust.Strategy.Design.Pattern"><strong><em>Download Source Code from GitHub</em></strong></a></blockquote><h3>Why This Matters</h3><p>In the fast-paced world of software development, requirements change. In my previous article on <a href="https://medium.com/@aman.toumaj/mastering-domain-driven-design-a-tactical-ddd-implementation-5255d71d609f">Tactical DDD</a>, I discussed how domain logic should be protected. The Strategy Pattern is a tactical tool that keeps your domain services clean.</p><p>By implementing it this way:</p><ul><li><strong>Your code is Extensible:</strong> Adding a “Weekly” tax rate requires zero changes to existing classes.</li><li><strong>Your code is Safe:</strong> The system crashes on misconfiguration rather than calculating wrong financial data.</li></ul><h3>Conclusion</h3><p>Don’t let your business logic drown in conditional statements. Use the Strategy Pattern to create a system that is as flexible as your business requirements. By moving away from conditional logic and into a Strategy-based architecture, we’ve achieved:</p><ol><li><strong>Testability:</strong> Each tax rule can be tested in isolation.</li><li><strong>Maintainability:</strong> New tax types don’t break old code.</li><li><strong>Reliability:</strong> The system refuses to perform “guesswork” with unknown data.</li></ol><p><strong>Thank you for following along with this Article! If you found this helpful, feel free to share it with your fellow developers. Happy coding!</strong></p><h3>Source Code</h3><p>For those who want to dive straight into the implementation, the complete source code is available on my GitHub: <strong>→ </strong><a href="https://github.com/tomajexpress/Robust.Strategy.Design.Pattern"><strong>Download Source Code from GitHub</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ecb3003f2dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Domain-Driven Design: A Tactical DDD Implementation]]></title>
            <link>https://medium.com/@aman.toumaj/mastering-domain-driven-design-a-tactical-ddd-implementation-5255d71d609f?source=rss-c93d326732df------2</link>
            <guid isPermaLink="false">https://medium.com/p/5255d71d609f</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Aman Toumaj]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 23:39:33 GMT</pubDate>
            <atom:updated>2026-02-04T20:20:54.268Z</atom:updated>
            <content:encoded><![CDATA[<p>Mastering Complexity in <strong>.NET 10</strong>: A Step-by-Step Guide to <strong>Domain-Driven Design</strong>. Move beyond basic CRUD and learn to architect a scalable E-Commerce API. This deep-dive features <strong>Rich Domain Models</strong>, integration with <strong>External Tax Services</strong>, a <strong>Secure Data Access Layer</strong>, and a rock-solid <strong>Clean Architecture</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-hxDSVN9rOiPbfUIxuCtQ.jpeg" /></figure><h3>Introduction</h3><p>In the fast-evolving landscape of Software development, the challenge isn’t just writing code that works — it’s writing code that remains maintainable as business logic grows.</p><p>In this article, we will explore how to build a robust <strong>E-Commerce</strong> <strong>ASP.NET 10 Web API</strong> using a <strong>Tactical Domain-Driven Design (DDD)</strong> approach. In a real-world enterprise E-Commerce ecosystem, the system is naturally divided into several distinct <strong>Bounded Contexts</strong>, such as <strong>Basket (Cart)</strong> for temporary storage, <strong>Payment</strong> for financial transactions, and <strong>Catalog</strong> for product inventory. However, to master the tactical patterns of Domain-Driven Design without becoming overwhelmed by infrastructure, this article focuses exclusively on the <strong>Order Management Context</strong>. By narrowing our lens to this specific domain, we can deep-dive into the implementation of complex business rules, rich domain entities, and the lifecycle of an Order, ensuring a robust foundation that can later be integrated into a full microservices or modular monolithic architecture.</p><p>We will move beyond basic CRUD operations to implement a sophisticated data access layer using the <strong>Generic Repository</strong> and <strong>Unit of Work</strong> patterns. By the end of this guide, you will see how these patterns work together within <strong>EF Core 10</strong> to create a system for managing customer orders that is clean, testable, and strictly decoupled.</p><h4>The Prerequisites</h4><p>To get the most out of this implementation, you should be comfortable with:</p><ul><li><strong>Object-Oriented Programming (OOP):</strong> The core of everything we’ll build.</li><li><strong>SOLID Principles:</strong> The architectural backbone of maintainable software.</li><li><strong>Entity Framework Core:</strong> Our primary ORM for data persistence.</li><li><strong>The DDD Mindset:</strong> An understanding of how to focus on the domain logic rather than just the database schema.</li></ul><h3>Source Code</h3><p>For those who want to dive straight into the implementation, the complete source code is available on my GitHub: <strong>→ </strong><a href="https://github.com/tomajexpress/Domain.Driven.Implementation.In.CSharp.NET.Core.git"><strong>Download Source Code from GitHub</strong></a></p><h3>Understanding Tactical DDD: Architectural Theory Before the Deep Dive</h3><p>Before we open the IDE and begin our implementation, it is crucial to understand the ‘Why’ behind our architectural choices. Mastering <strong>Onion Architecture</strong>, the <strong>Repository Pattern</strong>, and <strong>Unit of Work</strong> is about more than just adding layers or classes — it is about designing a strategic foundation for data persistence and business logic isolation that ensures your system remains maintainable for years to come. Architecture is the art of drawing boundaries. Before we write a single line of code, let’s explore the theory behind our stack.</p><h4><strong>Domain-Driven Design (DDD)</strong></h4><p>The term <strong>Domain-Driven Design (DDD)</strong> was coined by Eric Evans in 2004, but its relevance has only grown as systems become more distributed and complex. While DDD is a vast subject, our focus here is on <strong>Tactical Implementation</strong>.</p><p>Our goal is simple but powerful: <strong>Keep the business logic safe within the Domain.</strong> By focusing on “Rich Entities” and Domain Services, we ensure that our application logic remains independent of data persistence concerns. As Martin Fowler famously noted:</p><blockquote><em>“Domain-Driven Design is an approach to software development that centers the development on programming a domain model that has a rich understanding of the processes and rules of a domain.”</em></blockquote><h4>The Building Blocks</h4><p>To implement this, we will utilize the core tactical elements of DDD:</p><ul><li><strong>Entities &amp; Value Objects:</strong> The heartbeat of our business logic.</li><li><strong>Aggregate Roots:</strong> The entry points that ensure data consistency.</li><li><strong>Repositories:</strong> The abstraction that treats our database like an in-memory collection.</li><li><strong>Domain Services:</strong> Where logic that doesn’t belong to a single entity lives.</li></ul><h4>Onion Architecture</h4><p>The most effective way to implement DDD is through <strong>Onion Architecture</strong>. In this model, the <strong>Application Core</strong> (Domain Models and Services) sits at the very center. It has zero dependencies on external frameworks, databases, or UI layers. The “Dependency Inversion” is the secret to <strong>Testability and Agility</strong>. Because the business logic is isolated from the database and external APIs, we can test and debug our core rules in total isolation — without ever spinning up a SQL Server or an external service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*U3jNYth1pBFkIijHpwxpaA.png" /><figcaption>A visual representation of Tactical Domain-Driven Design: Centering the application on a rich domain model while decoupling infrastructure and data persistence through specialized patterns.</figcaption></figure><p>The primary strength of the <strong>Onion Architecture</strong> is its modularity. By placing the Domain at the center, we decouple our business logic from external concerns. This means that in the future, you can swap out your database, migrate to a different ORM, or completely redesign the UI without touching the core logic.</p><p>Because the inner layers (the <strong>Core Domain</strong>) have no dependencies on the outer layers, the system remains stable and predictable regardless of how the infrastructure evolves. If you’re looking for a deep dive into the theoretical background, a quick search for <em>“Domain-Driven Design Strategic Patterns”</em> will provide excellent context. Our goal today is to see how these concepts actually look in code.</p><h4>The Repository Pattern: Bridging the Domain and Data</h4><p>The <strong>Repository</strong> is one of the fundamental building blocks of Tactical DDD. It provides a clean, testable, and maintainable strategy for data access. As Martin Fowler famously defined it:</p><blockquote><em>“A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection, that isolates business entities from the underlying data infrastructure.”</em></blockquote><p>By treating the database as an in-memory collection, the Repository pattern enables <strong>Persistence Ignorance</strong>. This allows our domain entities to remain entirely unaware of how they are stored — whether it’s SQL Server, a NoSQL database, or an external API.</p><h4>Core Advantages</h4><ul><li><strong>Loose Coupling:</strong> By interacting only with interfaces, our application layers can evolve independently.</li><li><strong>Isolated Testing:</strong> We can test business logic in total isolation from external dependencies by mocking the repository interfaces.</li><li><strong>DRY Principle:</strong> It allows us to centralize and encapsulate complex queries, making them reusable across the entire application.</li></ul><h4>Applying the Dependency Inversion Principle (DIP)</h4><p>As illustrated in the diagram below, the <strong>Application Logic Layer</strong> does not point directly to the database or a concrete storage class. Instead, it points upward to the <strong>ICustomerRepository </strong>interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*yoPm6DAmJqc4kq5FY3eYDw.png" /><figcaption>Decoupling through Abstraction: Utilizing the Dependency Inversion Principle to ensure Application Services interact only with interfaces, keeping business logic agnostic of data access implementations.</figcaption></figure><h4>Decoupling through Abstraction</h4><p>By utilizing the <strong>Dependency Inversion Principle</strong>, we ensure that Application Services interact only with abstractions (interfaces). This keeps your core business logic strictly agnostic of data access implementations. In this architecture:</p><ul><li><strong>The Application Core defines the contract:</strong> It dictates <em>what</em> it needs (e.g., “I need to save a customer”) via the <strong>ICustomerRepository Interface</strong>.</li><li><strong>The Infrastructure Layer fulfills the contract:</strong> The concrete <strong>Customer Repository</strong> implementation sits &quot;outside&quot; the core, handling the technical details of communicating with the database.</li></ul><h4>Testability and Isolation</h4><p>By depending on these abstractions rather than concrete implementations, we unlock one of the most significant benefits of this pattern: <strong>High-Fidelity Unit Testing</strong>.</p><p>Because our Application Services rely on interfaces provided via <strong>Dependency Injection (DI)</strong>, we can easily “mock” the repository layer. This allows us to test business logic in total isolation, without the need for a live database, connection strings, or complex environmental setup. The result is a test suite that is fast, reliable, and strictly focused on verifying business rules — adhering to the core principles of a truly testable and agile architecture.</p><h4>Why this is “Dependency Inversion” in Action</h4><p>Traditionally, high-level logic depends on low-level details. We have <strong>inverted</strong> that relationship. Now, the low-level database implementation depends on the high-level definitions set by the Application layer.</p><p>This keeps your domain logic “safe” and future-proof. You can change your database schema, swap SQL Server for MongoDB, or migrate to a new ORM without breaking a single line of business logic. You are no longer building your logic on top of a database; you are building a database to support your logic.</p><h4>The Unit of Work Pattern: Ensuring Atomic Consistency</h4><p>The <strong>Unit of Work</strong> design pattern is essential for coordinating data persistence across multiple repositories. It manages the changes made to various business objects and ensures they are treated as a single, <strong>atomic transaction</strong>. This guarantees a critical “all-or-nothing” outcome: either the entire transaction is successfully committed, or every change is rolled back to maintain a consistent state.</p><h4>Encapsulating Repository Coordination</h4><p>As illustrated in the diagram below, the Unit of Work acts as an orchestrator. It encapsulates multiple repositories and — most importantly — <strong>shares a single database context</strong> between them. By centralizing the <strong>SaveChanges()</strong> operation, it prevents partial data updates and ensures that your domain logic remains clean and transactionally sound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*DRnwk7kKXhQLVbwEqG1MXQ.png" /><figcaption>The Unit of Work Pattern: Coordinating multiple repositories within a single atomic transaction to ensure data integrity and consistent state across the application core.</figcaption></figure><h3>Business Requirements &amp; Domain Specifications: Orders Management Context</h3><p>Before diving into the code, we must define the business rules we are trying to solve. In our E-commerce system, the <strong>Order</strong> is more than just a table in a database; it is a legal and financial contract between the customer and the store.</p><h4>1. The Core Requirements</h4><p>Our domain model must satisfy the following rules to be considered “valid”:</p><ul><li><strong>Identity &amp; Traceability:</strong> Every order must have a unique OrderId and a TrackingNumber generated upon creation.</li><li><strong>Customer Linkage:</strong> An order cannot exist without a valid CustomerId.</li><li><strong>Shipping Integrity:</strong> A physical Shipping Address is mandatory; we cannot ship products to nowhere.</li><li><strong>The “No Empty Orders” Rule:</strong> An Order aggregate is only valid if it contains at least one OrderItem. Order constructor enforces this to prevent &quot;ghost orders&quot; in the database.</li></ul><h4>2. Financial Consistency (The Price Invariant)</h4><p>This is where our OrderItem and Price Value Object come into play:</p><ul><li><strong>Price Snapshot:</strong> When an item is added to an order, we must capture its price at that specific moment. Even if the store changes the product price tomorrow, the customer’s historical order price must remain unchanged to the value at the time of purchase (<strong>Immutability</strong>).</li><li><strong>Global Price Limits:</strong> To prevent fraud or data-entry errors, the system must enforce a Maximum Price Limit per currency unit (e.g., USD, EUR) for every order.</li></ul><h4>3. The Order Lifecycle</h4><p>An order is a “living” entity that moves through specific states. We must prevent illegal transitions. To protect the integrity of the physical shipping process, we enforce a strict state machine:</p><ul><li><strong>Allowed Flow:</strong> Created — &gt;Pending — &gt;Shipped — &gt;Delivered.</li><li><strong>Cancellations:</strong> Customers can only cancel an order if it is still in the Created state. Once the order is Pending (payment processing) or Shipped, the &quot;Cancel&quot; operation is forbidden by the domain logic to prevent logistics conflicts.</li><li><strong>The Shipping Rule:</strong> An order cannot move to Shipped unless it has been successfully transitioned to Pending first.</li></ul><h4>4. Tax Calculation Service (External Invariant)</h4><p>Tax logic is complex and changes based on regional laws; therefore, it does not belong inside the Order entity itself.</p><ul><li><strong>When to Apply:</strong> Tax must be calculated and added to the order <strong>immediately after</strong> the items are added but <strong>before</strong> the order is finalized/paid.</li><li><strong>Where it Lives:</strong> We define an ITaxCalculationService in Domain Service. The implementation resides in the <strong>Infrastructure Layer</strong> (calling a Tax API), but the <strong>Domain Layer</strong> dictates when and how the result is attached to the Order.</li></ul><h4>Why Defining These Rules Matters for Technical Implementation</h4><p>By defining these rules clearly, we justify our technical choices:</p><ol><li><strong>Private Setters:</strong> Used on the Status property so that only internal methods like CancelOrder() can trigger changes, preventing illegal state jumps.</li><li><strong>Init Setters:</strong> To ensure the Price captured at checkout remains immutable.</li><li><strong>Domain Validation:</strong> To ensure that the “Minimum Order” and “Max Price” rules are checked inside the Order constructor before the object is ever saved to the database.</li><li><strong>Guard Clauses:</strong> We use BusinessRuleBrokenException to immediately halt the execution if a developer tries to ship an order that hasn&#39;t been paid for.</li></ol><h3>Domain Class Diagram Of Orders Management Context: A DDD Perspective</h3><p>A class diagram in <strong>Domain-Driven Design</strong> is more than just a map of properties; it is a blueprint of business rules and lifecycle boundaries. The following is a class diagram showing how we interpret the relationships in our order domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3n_3rxdJHzB3yu8GNxB6Q.png" /><figcaption>Orders Management Class Diagram</figcaption></figure><h4>1. The Aggregate Root (Order)</h4><p>As you can see from the class diagram above, the Order class is the &quot;Entry Point&quot; or <strong>Aggregate Root</strong>.</p><ul><li><strong>The Rule:</strong> Any change to an order (like adding an item or changing a status) must go through this class.</li><li><strong>The Implementation:</strong> Notice how methods like AddOrderItem and MarkAsShipped are inside Order. This ensures that business invariants (like the &quot;Maximum Price Limit&quot;) are checked every time the data changes.</li></ul><h4>2. Entities vs. Value Objects</h4><p>In the diagram, you will see two distinct types of objects:</p><ul><li><strong>Entities (Order &amp; OrderItem):</strong> These have an Id. Even if two Order Items have the same product and price, they are distinct because they are separate rows in the database.</li><li><strong>Value Objects (Price):</strong> These are defined by their attributes. A Price of $100 USD is identical to any other Price of $100 USD. We use the record type in C# to ensure these are immutable—you don&#39;t &quot;change&quot; a price; you replace it with a new one.</li></ul><h4>3. Understanding the Associations</h4><ul><li><strong>The “One-to-Many” Arrow:</strong> The line from Order to OrderItem (shown as a collection association) represents the <strong>Aggregate Boundary</strong>. It tells us that OrderItems belong strictly to an Order and should not be modified independently.</li><li><strong>The Association to Price:</strong> The arrow pointing to the Price record indicates that the OrderItem &quot;owns&quot; its price at the time of purchase. This is crucial for historical data—if a product price changes in the catalog later, the price stored inside this OrderItem stays locked.</li></ul><h4>4. Supporting Structures</h4><ul><li><strong>Enums (OrderStatus, Currency):</strong> These define the strict states our system can occupy. By using Enums, we prevent “magic strings” from causing bugs in our logic.</li><li><strong>Static Domain Services (MaximumPriceLimits):</strong> Some rules don’t belong to a single object but to the whole system. This static utility acts as a central policy that the Order entity consults during the validation process.</li></ul><p>Now that we understand the business constraints, let’s look at how we use C# 12/13 features to turn these ‘soft’ business rules into ‘hard’ compiler-enforced logic.</p><h3>Project Setup and Solution Architecture</h3><p>We begin by establishing a robust structure that supports the Onion Architecture principles. We will also implement all the previous topics such as domain models, entities, value objects, application services, repository and unit of work patterns together.</p><h4>1. Creating the Solution</h4><p>Open <strong>Visual Studio 2022</strong> (or later) and create a new <strong>Blank Solution</strong> named DomainDrivenTutorial To keep our infrastructure separate from our core logic, we will organize the solution using <strong>Solution Folders</strong>. Start by creating a folder named Framework.Core</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*-UDIYwgS2a3HVVoylIXx2Q.jpeg" /><figcaption>Framework.Core Folder &amp; SharedKernel Class Library</figcaption></figure><h4>2. Implementing the Shared Kernel</h4><p>Within the Framework.Core folder, we add a new <strong>.NET 10 Class Library</strong> named SharedKernel</p><p>The <strong>Shared Kernel</strong> is a critical DDD pattern. It houses common types, constants, and helper classes that are globally applicable across all layers of the solution. By isolating these tools here, we avoid code duplication while maintaining a “Single Source of Truth.”</p><h4>The PageParam Model</h4><p>To handle data pagination consistently across the Repositories and Application Services, we create a Models folder within the SharedKernel project and add the PageParam.cs record.</p><pre>namespace SharedKernel.Models;<br><br>public record PageParam<br>{<br>    private const int MaxPageSize = 50;<br>    private int _pageSize = 10;<br><br>    public int PageNumber { get; init; } = 1;<br><br>    public int PageSize<br>    {<br>        get =&gt; _pageSize;<br>        init =&gt; _pageSize = value &gt; MaxPageSize ? MaxPageSize : value;<br>    }<br>}</pre><h4>The IAggregateRoot Interface</h4><p>In Domain-Driven Design, not every entity is accessible from the outside. We only interact with an <strong>Aggregate Root</strong>. This interface acts as a “marker,” allowing our Generic Repository to constrain its operations only to roots, ensuring we don’t accidentally modify a child entity (like an OrderItem) without going through its parent (Order). To maintain a strict hierarchy within our domain, we introduce the <strong>IAggregateRoot</strong> marker interface. This interface serves as a gatekeeper, ensuring that our repositories only handle top-level entities.</p><pre>namespace SharedKernel.Models;<br><br>/// &lt;summary&gt;<br>/// A marker interface to identify Aggregate Roots.<br>/// &lt;/summary&gt;<br>public interface IAggregateRoot;</pre><h3>Implementing the Generic Repository with EF Core</h3><p>With our foundation in place, we now move to the <strong>Infrastructure</strong> layer of our framework. We will create a specialized libraries to handle data persistence using Entity Framework Core.</p><h4>1. Creating the Infrastructure Library GenericRepository.Abstractions</h4><p>Add a new <strong>.NET 10 Class Library</strong> to the Framework.Core folder named GenericRepository.Abstractions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*UhDd_Zm85v2L5jN5nIrjUA.png" /><figcaption>Framework.Core Folder &amp; GenericRepository Class Libraries</figcaption></figure><h4>The Generic Repository: A Universal Contract</h4><p>GenericRepository.Abstractions library is designed to be lean and focused, containing only core interface files:</p><ul><li><strong>IGenericRepository.cs</strong>: The abstraction defining our data operations.</li></ul><pre>namespace GenericRepository.Abstractions;<br><br>public interface IGenericRepository&lt;TEntity&gt; where TEntity : class, IAggregateRoot<br>{<br>    void Add(TEntity entity);<br>    void Update(TEntity entity);<br>    void Remove(TEntity entity);<br><br>    Task&lt;TEntity?&gt; GetByIdAsync(object id);<br>    Task&lt;TEntity?&gt; GetAsync(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate, params Expression&lt;Func&lt;TEntity, object&gt;&gt;[] includes);<br><br>    Task&lt;IEnumerable&lt;TEntity&gt;&gt; GetAllAsync();<br>    Task&lt;IEnumerable&lt;TEntity&gt;&gt; GetAllAsync&lt;TProperty&gt;(Expression&lt;Func&lt;TEntity, TProperty&gt;&gt; include);<br><br>    Task&lt;TEntity?&gt; SingleOrDefaultAsync(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate);<br><br>    Task&lt;QueryResult&lt;TEntity&gt;&gt; GetPageAsync(<br>        QueryObjectParams queryObjectParams,<br>        Expression&lt;Func&lt;TEntity, bool&gt;&gt;? predicate = null,<br>        params Expression&lt;Func&lt;TEntity, object&gt;&gt;[] includes);<br>}</pre><p>The IGenericRepository&lt;TEntity&gt; is the blueprint for how our application interacts with the database. This interface acts as a <strong>reusable contract</strong> for all data operations. Instead of creating individual repositories with redundant code, we define a set of common operations that can be applied to any entity that qualifies as an <strong>Aggregate Root</strong>.</p><h4>2. Creating the Infrastructure Library GenericRepository.EntityFramework</h4><p>We add a new <strong>.NET 10 Class Library</strong> to the Framework.Core folder named GenericRepository.EntityFramework</p><p>This library is designed to be lean and focused, containing only two core files:</p><ul><li><strong>GenericRepository.cs</strong>: The concrete implementation leveraging EF Core.</li><li><strong>SortingExtension.cs</strong>: A static helper class to handle dynamic IQueryable sorting based on our SortParam model.</li></ul><h4>Managing Dependencies</h4><p>Once the project is created, remember to add a <strong>Project Reference</strong> to GenericRepository.Abstractions. To leverage the power of EF Core, we also need to install the necessary libraries. In a modern .NET environment, we aim for the latest stable versions of the Microsoft packages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*R3KweEkA0tD6o_U57sTyfQ.png" /><figcaption>Right-click on the Solution and select Manage NuGet Packages for Solution…</figcaption></figure><ol><li>Right-click on the <strong>Solution</strong> and select <strong>Manage NuGet Packages for Solution</strong></li><li>Navigate to the <strong>Browse</strong> tab and search for Microsoft.EntityFrameworkCore</li><li>Select the <strong>GenericRepository.EntityFramework</strong> project and click <strong>Install</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7Fgfbl0NnP5SMjPBsYAww.jpeg" /><figcaption>Navigate to the <strong>Browse</strong> tab and search for Microsoft.EntityFrameworkCore</figcaption></figure><h4>Alternative: Installing <strong>NuGet Package</strong> via .NET CLI (Bash)</h4><p>If you prefer using the terminal over the GUI, you can install the required packages quickly using the following Bash commands. Ensure you are in the root directory of your solution:</p><pre># Target the specific Generic Repository project<br>dotnet add src/Framework.Core/GenericRepository.EntityFramework package Microsoft.EntityFrameworkCore</pre><blockquote><strong><em>Pro-Tip:</em></strong><em> For a fully functional repository, you will likely also want to install </em><em>Microsoft.EntityFrameworkCore.Relational if you plan on using common relational database features across different providers.</em></blockquote><h4>The GenericRepository Class Implementation</h4><p>Now that we have established our infrastructure library and dependencies, let’s look at a concrete implementation. The following code snippet demonstrates how to translate the Repository Pattern into a functional C# class using <strong>Entity Framework Core</strong>.</p><p>Pay close attention to how we use the <strong>Generic Type Constraint</strong> (where T : class) to ensure that our repository only handles reference types that have implemented the IAggregateRoot marker interface, and how we leverage <strong>Asynchronous Programming</strong> to keep our application responsive and scalable.</p><pre>namespace GenericRepository.EntityFramework;<br><br>public class GenericRepository&lt;TEntity&gt;(DbContext context) : IGenericRepository&lt;TEntity&gt;<br>    where TEntity : class, IAggregateRoot<br>{<br>    protected readonly DbContext Context = context ?? throw new ArgumentNullException(nameof(context));<br>    private readonly DbSet&lt;TEntity&gt; _dbSet = context.Set&lt;TEntity&gt;();<br><br>    public virtual void Add(TEntity entity) =&gt; _dbSet.Add(entity);<br>    public virtual void Update(TEntity entity) =&gt; _dbSet.Update(entity);<br>    public virtual void Remove(TEntity entity) =&gt; _dbSet.Remove(entity);<br><br>    public async Task&lt;TEntity?&gt; GetByIdAsync(object id) =&gt; await _dbSet.FindAsync(id).ConfigureAwait(false);<br>    public virtual async Task&lt;TEntity?&gt; GetAsync(<br>    Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate,<br>    params Expression&lt;Func&lt;TEntity, object&gt;&gt;[] includes)<br>    {<br>        IQueryable&lt;TEntity&gt; query = _dbSet;<br><br>        if (includes is { Length: &gt; 0 })<br>        {<br>            query = includes.Aggregate(query, (current, include) =&gt; current.Include(include));<br>        }<br><br>        return await query.FirstOrDefaultAsync(predicate).ConfigureAwait(false);<br>    }<br><br>    public async Task&lt;IEnumerable&lt;TEntity&gt;&gt; GetAllAsync() =&gt; await _dbSet.AsNoTracking().ToListAsync().ConfigureAwait(false);<br><br>    public async Task&lt;IEnumerable&lt;TEntity&gt;&gt; GetAllAsync&lt;TProperty&gt;(Expression&lt;Func&lt;TEntity, TProperty&gt;&gt; include)<br>    {<br>        return await _dbSet.Include(include).AsNoTracking().ToListAsync().ConfigureAwait(false);<br>    }<br><br>    public async Task&lt;TEntity?&gt; SingleOrDefaultAsync(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate) =&gt;<br>        await _dbSet.SingleOrDefaultAsync(predicate).ConfigureAwait(false);<br><br>    public virtual async Task&lt;QueryResult&lt;TEntity&gt;&gt; GetPageAsync(<br>        QueryObjectParams queryObjectParams,<br>        Expression&lt;Func&lt;TEntity, bool&gt;&gt;? predicate = null,<br>        params Expression&lt;Func&lt;TEntity, object&gt;&gt;[] includes)<br>    {<br>        IQueryable&lt;TEntity&gt; query = _dbSet;<br><br>        if (includes is { Length: &gt; 0 })<br>        {<br>            query = includes.Aggregate(query, (current, include) =&gt; current.Include(include));<br>        }<br><br>        if (predicate is not null)<br>        {<br>            query = query.Where(predicate);<br>        }<br><br>        var totalCount = await query.CountAsync().ConfigureAwait(false);<br><br>        if (queryObjectParams.SortingParams is { Count: &gt; 0 })<br>        {<br>            query = SortingExtension.GetOrdering(query, queryObjectParams.SortingParams)!;<br>        }<br><br>        var items = await query<br>            .Skip((queryObjectParams.PageNumber - 1) * queryObjectParams.PageSize)<br>            .Take(queryObjectParams.PageSize)<br>            .AsNoTracking()<br>            .ToListAsync()<br>            .ConfigureAwait(false);<br><br>        return new QueryResult&lt;TEntity&gt;(items, totalCount);<br>    }<br>}</pre><h4>Extensibility through Protected Access</h4><p>In the previous generic repository code, you will notice that the DbContext is intentionally defined as a <strong>protected</strong> property within the base Repository class. This is a strategic design choice to support the <strong>&quot;is-a&quot; relationship</strong> between the generic repository and its specialized descendants.</p><p>By exposing the context to derived classes, we enable specialized repositories (like an OrderRepository) to move beyond standard CRUD operations. This allows for:</p><ul><li><strong>Complex Querying:</strong> Crafting optimized, high-performance queries using specialized EF Core features (like TagWith, IgnoreQueryFilters, or complex GroupBy logic).</li><li><strong>Domain-Specific Logic:</strong> Implementing queries that are unique to a specific aggregate root and don’t belong in a one-size-fits-all generic implementation.</li><li><strong>Flexibility:</strong> Ensuring that while we benefit from the boilerplate reduction of a generic base, we are never “locked out” of the underlying power of the database context when the domain requires it.</li></ul><h3>Hands-on: Building a DDD-Based ASP.NET Core <strong>E-Commerce API</strong></h3><p>Now that we have built our generic infrastructure, it is time to apply these patterns to a real-world scenario. We will build a clean, scalable <strong>E-Commerce API</strong> to demonstrate how Domain-Driven Design (DDD) handles complex business logic while maintaining a strict separation of concerns.</p><h4>The Architectural Goal</h4><p>Our primary objective is <strong>Persistence Ignorance</strong>. We want our business logic (Domain) to remain entirely unaware of how data is stored. To achieve this, we will implement the <strong>Order Aggregate</strong>, consisting of the Order and OrderItem entities. By the end of this section, we will have:</p><ul><li><strong>Encapsulated Logic:</strong> Moving business rules into Domain Models and Services.</li><li><strong>Aggregate Roots:</strong> Ensuring data integrity by treating the Order and its Items as a single unit.</li><li><strong>Decoupled Layers:</strong> Using a dedicated Class Library for our Core logic, keeping it isolated from the Web API project.</li></ul><h4>Setting Up the Core Layer</h4><p>To keep our solution organized, we will group our business-specific projects into a dedicated solution folder.</p><ol><li>Right-click on your Solution and create a new Solution Folder named <strong>EShoppingTutotial</strong></li><li>Inside this folder, add a new <strong>.NET 10 Class Library</strong> named <strong>EShoppingTutorial.Core.Domain</strong></li><li>Inside this folder, we add another new <strong>.NET 10 Class Library</strong> named <strong>EShoppingTutorial.Core.Persistence</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*apL9ei3Bo-2nCSIURooxYQ.png" /><figcaption>Adding a new .NET 10 Class Library named EShoppingTutorial.Core.Domain</figcaption></figure><p>This Core.Domain project will be the brain of our application. It will contain our Entities, Value Objects, Domain Services, and the Repository Interfaces that define how the rest of the system interacts with our data.</p><h4>Designing the Solution Structure: A Blueprint for Clean Architecture</h4><p>Before we dive more into the code, we must establish a clear solution structure. As seen in the image below, our EShoppingTutorial.Core projects are organized into distinct boundaries: <strong>Core</strong>.<strong>Domain</strong> and <strong>Core</strong>.<strong>Persistence</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*gEF6uYz1L6Glz-pgYIlnPQ.png" /><figcaption>Solution Structure: A Blueprint for Clean Architecture</figcaption></figure><p>This separation is the cornerstone of <strong>Clean Architecture</strong> and <strong>Domain-Driven Design</strong>. By isolating our business logic from data access concerns, we ensure the system remains maintainable, testable, and resilient to change.</p><h4>The Core Philosophy: Stability vs. Volatility</h4><p>At its heart, this architecture is a strategic play between what is <strong>constant</strong> and what is <strong>changeable. </strong>The primary goal of this structure is to separate <strong>Persistence Ignorant</strong> code from infrastructure details. To achieve this, we divide the system into two distinct zones based on their rate of change:</p><ul><li><strong>The Stable Core (Core.Domain):</strong> This layer contains the “heart” of our application — entities, value objects, and domain services. These represent the business invariants that rarely change, regardless of technology. By keeping them isolated, we ensure that our business rules are never polluted by database-specific logic or ORM requirements.</li><li><strong>The Volatile Detail (Core.Persistence):</strong> This layer handles the “how” of data storage. It is home to our EF Core mappings, migrations, and concrete repository implementations. By separating this from the Domain, we gain the flexibility to swap databases or update ORM versions without ever touching our core domain business logic.</li></ul><h4>A Closer Look at the Structure</h4><p>The folder organization in our solution is not accidental; it is a physical manifestation of the <strong>Separation of Concerns</strong>. By intentionally dividing our projects into Domain, Entities, Services, and Persistence, we enforce a strict dependency flow.</p><ul><li><strong>Entities &amp; Value Objects:</strong> The fundamental building blocks of our domain.</li><li><strong>Domain Services:</strong> Orchestrates complex logic that doesn’t naturally fit within a single entity.</li><li><strong>Repositories (Core.Domain):</strong> Contains the <strong>Interfaces</strong> that define what data operations are needed.</li><li><strong>Repositories (Core.Persistence):</strong> Contains the concrete <strong>Implementations</strong> that talk to the database.</li></ul><blockquote><strong>The Architectural Goal: </strong>We separate the “stable” from the “volatile.”</blockquote><h4>Preparing the Infrastructure Core.Persistence with NuGet</h4><p>With our structure established, we need to bring in the necessary tooling. Since we are utilizing <strong>Entity Framework Core</strong> for our persistence logic, we need to add the required packages to the solution.</p><ol><li>Right-click on the <strong>Solution</strong> and select <strong>Manage NuGet Packages for Solution</strong>.</li><li>As seen in the image below, in the <strong>Browse</strong> tab, search for Microsoft.EntityFrameworkCore</li><li>Select the relevant projects (specifically the Core.Persistence) and install the latest stable version.</li><li>Repeat this scenario for NuGet packages Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore.Tools</li><li>Furthermore, in Core.Persistence project we need to add project references to the project libraries GenericRepository.EntityFramework and Shared Kernel</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_5PGUtNaS1e48RuxZmQTsw.png" /><figcaption>Navigate to the <strong>Browse</strong> tab and search for Microsoft.EntityFrameworkCore</figcaption></figure><p>By installing these at the solution level, we can ensure version consistency across all our projects, preventing the “dependency hell” that often plagues larger applications.</p><blockquote>“Clean Architecture is not just about where you put your files; it’s about how you protect your boundaries.“</blockquote><h4>Domain Exceptions: Enforcing Business Rules and Handling Failures</h4><p>In a robust Domain Model, we need a clear way to define the limits of our system and a consistent way to signal when those limits are breached.</p><p>When a business rule is violated (like exceeding the price limit), we shouldn’t just throw a generic Exception. We need a semantic way to say, <em>&quot;The user did something that is not allowed by the domain.&quot;</em></p><p>We create a custom BusinessRuleBrokenException in the SharedKernel project. This distinguishes <strong>domain errors</strong> (logic violations) from <strong>system errors</strong> (database connection failures, null references). This distinction is crucial for the API layer later, as it allows us to return a meaningful <strong>400 Bad Request</strong> to the client instead of a <strong>500 Internal Server Error</strong>.</p><pre>namespace SharedKernel.Exceptions;<br><br>/// &lt;summary&gt;<br>/// Base exception for all domain-specific exceptions.<br>/// &lt;/summary&gt;<br>public class BaseException(string? message = null, Exception? innerException = null)<br>    : Exception(message, innerException);<br><br>/// &lt;summary&gt;<br>/// Exception thrown when a specific domain business rule is violated.<br>/// &lt;/summary&gt;<br>public class BusinessRuleBrokenException(string message, Exception? innerException = null)<br>    : BaseException(message, innerException);</pre><h3>Modeling the Domain: Entities, Value Objects, and Enums</h3><p>According to the rules previously described in this article in the section “Business Requirements and Domain Specifications: Context of Orders Management”, we can now begin implementing our core business logic. This is where the “ubiquitous language” of our domain starts to take shape in code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3n_3rxdJHzB3yu8GNxB6Q.png" /><figcaption>Orders Management Class Diagram</figcaption></figure><p>We will populate the folders we established earlier with the following core components:</p><h4>1. Defining our Entities</h4><p>In the <strong>Entities</strong> folder, we will create the Order and OrderItem classes.</p><ul><li><strong>Order</strong>: This serves as our <strong>Aggregate Root</strong>, acting as the primary entry point for any operations related to a customer’s purchase.</li><li><strong>OrderItem</strong>: A child entity belonging to the Order aggregate, representing specific products and quantities.</li></ul><h4>2. Implementing Value Objects</h4><p>In the <strong>ValueObjects</strong> folder, we add the Price model. In DDD, a <strong>Value Object</strong> is defined by its attributes rather than a unique identity. By making Price a Value Object, we can encapsulate validation logic (e.g., ensuring a price is never negative) and keep our entities clean.</p><h4>3. Standardizing with Enums</h4><p>Finally, in the <strong>Enums</strong> folder, we define <strong>Currency</strong>. This allows us to standardize the currencies supported by our system (e.g., USD, EUR, RIAL) across the entire application.</p><h4>The <strong>Currency</strong> Enum: Handling Currency with Precision</h4><p>Located in the Enums folder of our <strong>Core.Domain</strong>, the <strong>Currency</strong> enum defines the currencies supported by our system. While it appears simple, its structure follows a critical defensive programming principle.</p><pre>namespace EShoppingTutorial.Core.Domain.Enums;<br><br>/// &lt;summary&gt;<br>/// Defines the currency units supported by the domain.<br>/// We explicitly set &#39;Unspecified = 0&#39; to prevent default-value logic errors.<br>/// &lt;/summary&gt;<br>public enum Currency<br>{<br>    Unspecified = 0,<br>    Rial = 1,<br>    USD = 2,<br>    EUR = 3,<br>}</pre><h4>The OrderStatus Enum: Defining the Workflow</h4><p>Located within the Enums folder of the <strong>Core.Domain</strong> layer, the OrderStatus enum serves as the single source of truth for our business process. By explicitly defining these states, we prevent &quot;magic numbers&quot; from leaking into our database or UI.</p><pre>namespace EShoppingTutorial.Core.Domain.Enums;<br><br>/// &lt;summary&gt;<br>/// Represents the life cycle of an Order.<br>/// &lt;/summary&gt;<br>public enum OrderStatus<br>{<br>    Created = 1,<br>    Pending = 2,<br>    Shipped = 3,<br>    Delivered = 4,<br>    Cancelled = 5<br>}</pre><h4>The Price Value Object: Making Money a First-Class Citizen</h4><p>Sometimes developers make the mistake of representing money as a simple Decimal. This leads to a dangerous situation where a developer might accidentally add <strong>10.00 USD</strong> to <strong>10.00 EUR</strong>, resulting in a mathematically correct but financially disastrous <strong>20.00</strong>. Creating a <strong>Price Value Object</strong> is one of the most effective ways to show the power of Domain-Driven Design (DDD).</p><p>In the ValueObjects folder, we implement the Price value object. Since Value Objects are defined by their values and should be immutable, the C# <strong>record</strong> is the perfect tool. It automatically handles value-based equality for us.</p><pre>namespace EShoppingTutorial.Core.Domain.ValueObjects;<br><br>public record Price<br>{<br>    public decimal Value { get; init; }<br>    public Currency Currency { get; init; } = Currency.Unspecified;<br><br>    // EF Core requires a parameterless constructor<br>    protected Price() { }<br><br>    public Price(decimal value, Currency currency)<br>    {<br>        if (Currency.Unspecified == currency)<br>        {<br>            throw new BusinessRuleBrokenException(&quot;You must supply a valid money currency!&quot;);<br>        }<br><br>        if (value &lt; 0)<br>        {<br>            throw new BusinessRuleBrokenException(&quot;Price value cannot be negative.&quot;);<br>        }<br><br>        Value = value;<br>        Currency = currency;<br>    }<br><br>    public bool HasValue =&gt; Currency != Currency.Unspecified &amp;&amp; Value &gt;= 0;<br><br>    public static Price operator +(Price left, Price right)<br>    {<br>        if (left.Currency != right.Currency)<br>            throw new BusinessRuleBrokenException(&quot;Cannot add different currencies.&quot;);<br><br>        return new Price(left.Value + right.Value, left.Currency);<br>    }<br><br>    public static Price operator -(Price left, Price right)<br>    {<br>        if (left.Currency != right.Currency)<br>            throw new BusinessRuleBrokenException(&quot;Cannot subtract different currencies.&quot;);<br><br>        return new Price(left.Value - right.Value, left.Currency);<br>    }<br><br>    public override string ToString() =&gt;<br>        Currency != Currency.Unspecified ?<br>        Value + &quot; &quot; + MoneySymbols.GetSymbol(Currency) :<br>        Value.ToString();<br>}</pre><h3>Why use C# Records?</h3><p>Value Objects are defined by their attributes, not their identity. Two five-dollar bills are identical in value, regardless of their serial numbers. Because of this, the <strong>C# record</strong> is the perfect tool for the job. It gives us:</p><ul><li><strong>Immutability:</strong> Once a price is set, it cannot be tampered with.</li><li><strong>Value-based Equality:</strong> Two Price objects are automatically considered equal if the value and currency match.</li></ul><blockquote><strong>Value Objects are the building blocks:</strong> of a stable Domain. By moving validation logic into the <strong>Price</strong> record itself, we simplify our Application Services. We no longer need to check for negative prices in our Services because the Domain ensures a negative <strong>Price</strong> object can&#39;t even exist.</blockquote><blockquote><strong>Overloading Operators for Value Objects:</strong> is more than just syntactic sugar; it’s about aligning our code with mathematical reality. By allowing the + operator, we treat Price as a first-class citizen in our domain, while still enforcing strict business rules—like preventing the accidental addition of USD to EUR—at the compiler level.</blockquote><h4>The Address Value Object: Curing Primitive Obsession</h4><p>In many applications, an address is treated as a simple String. This is a classic example of <strong>Primitive Obsession</strong>. When you use a raw string for an address, your code doesn&#39;t know what a &quot;City&quot; is, it can&#39;t easily validate a &quot;Zip Code,&quot; and it certainly can&#39;t guarantee that the data is geographically consistent.</p><p>By promoting the address to a <strong>Value Object</strong>, we transform it from “just a piece of text” into a first-class citizen of our Domain. We use a C# <strong>record</strong> here for its built-in value-based equality. In DDD, two addresses are considered the same if all their properties match, making records the perfect tool for the job.</p><pre>namespace EShoppingTutorial.Core.Domain.ValueObjects;<br><br>public record Address<br>{<br>    public string Street { get; init; } = default!;<br>    public string City { get; init; } = default!;<br>    public string Country { get; init; } = default!;<br>    public string ZipCode { get; init; } = default!;<br><br>    // EF Core requires a parameterless constructor<br>    protected Address() { }<br><br>    public Address(string street, string city, string country, string zipCode)<br>    {<br>        if (string.IsNullOrWhiteSpace(street)) throw new BusinessRuleBrokenException(&quot;Street is required.&quot;);<br>        if (string.IsNullOrWhiteSpace(city)) throw new BusinessRuleBrokenException(&quot;City is required.&quot;);<br>        if (string.IsNullOrWhiteSpace(country)) throw new BusinessRuleBrokenException(&quot;Country is required.&quot;);<br>        if (string.IsNullOrWhiteSpace(zipCode)) throw new BusinessRuleBrokenException(&quot;ZipCode is required.&quot;);<br><br>        Street = street;<br>        City = city;<br>        Country = country;<br>        ZipCode = zipCode;<br>    }<br><br>    public override string ToString() =&gt; $&quot;{Street}, {City}, {ZipCode}, {Country}&quot;;<br>}</pre><h4>The Power of Strongly Typed IDs</h4><p>As we refine our domain model, we want to eliminate the risk of “Primitive Obsession.” By default, developers use int or Guid for identifiers. However, this creates a vulnerability: the compiler cannot distinguish between an OrderId, a ProductId, or a CustomerId. They are all just integers. Introducing <strong>Strongly Typed IDs</strong> is a significant step up in Domain-Driven Design. It moves your architecture from being “technically correct” to being “domain-robust.”</p><p>By implementing <strong>Strongly Typed IDs</strong>, we wrap these primitives in unique types. This ensures that:</p><ul><li><strong>Compile-Time Safety:</strong> You cannot accidentally pass an OrderId to a method that requires a ProductId.</li><li><strong>Ubiquitous Language:</strong> The code more accurately reflects the business domain.</li><li><strong>Self-Documenting Code:</strong> Method signatures become much clearer (e.g., GetProduct(ProductId id) vs GetProduct(int id)).</li></ul><p>In .NET 10, the most efficient way to implement these is using <strong>Records</strong>. They provide value-based equality out of the box and are incredibly concise.</p><pre>using System.ComponentModel.DataAnnotations.Schema;<br><br>namespace EShoppingTutorial.Core.Domain.ValueObjects;<br><br>[NotMapped]<br>public record OrderId(int Value);<br><br>[NotMapped]<br>public record OrderItemId(int Value);<br><br>[NotMapped]<br>public record ProductId(int Value);<br><br>[NotMapped]<br>public record CustomerId(int Value);</pre><h4>Creating the GlobalUsings.cs File</h4><p>To keep our project clean and maintainable, we utilize <strong>Global Using Directives</strong>. By centralizing our common namespaces into a single GlobalUsings.cs file, we eliminate repetitive boilerplate code. This ensures that our classes remain focused strictly on behavior and business logic, significantly improving the &#39;signal-to-noise&#39; ratio of our codebase.</p><p>Creating a new file GlobalUsings.cs at the root of your EShoppingTutorial.Core.Domain project:</p><pre>// Standard .NET namespaces<br>global using System.Diagnostics.CodeAnalysis;<br><br>// Domain Specific Namespaces<br>global using SharedKernel.Exceptions;<br>global using SharedKernel.Models;<br>global using GenericRepository.Abstractions;<br>global using EShoppingTutorial.Core.Domain.Entities;<br>global using EShoppingTutorial.Core.Domain.Enums;<br>global using EShoppingTutorial.Core.Domain.ValueObjects;<br>global using EShoppingTutorial.Core.Domain.InvariantRules;<br>global using EShoppingTutorial.Core.Domain.Repositories;<br>global using EShoppingTutorial.Core.Domain.Services;</pre><h3>Ready to dive into the Core of Domain Logic</h3><p>Now we are ready to move to the heart of our domain logic. We will implement the OrderItem and Order entities, demonstrating how to use the base classes we created earlier while strictly following <strong>Domain-Driven Design (DDD)</strong> principles to ensure data integrity.</p><h4>Implementing the OrderItem Entity</h4><p>The <strong>OrderItem</strong> is a child entity within the <strong>Order Aggregate</strong>. It has its own identity but cannot exist independently of an Order. First we implement the <strong>OrderItem</strong> entity within our Entities folder.</p><pre>namespace EShoppingTutorial.Core.Domain.Entities;<br><br>public class OrderItem<br>{<br>    // This is Id generated by EF, so it&#39;s not &#39;required&#39; at creation. So we initialize with default! to silence the warning<br>    public OrderItemId Id { get; protected set; } = default!; <br><br>    public required ProductId ProductId { get; init; }<br><br>    public required Price Price { get; init; }<br><br>    // This is the Foreign Key generated by EF, so it&#39;s not &#39;required&#39; at creation<br>    public OrderId OrderId { get; protected set; } = default!;<br><br>    // EF Core requires a parameterless constructor<br>    protected OrderItem() { }<br><br>    [SetsRequiredMembers] <br>    public OrderItem(ProductId productId, Price price)<br>    {<br>        ProductId = productId ?? throw new ArgumentNullException(nameof(productId));<br>        Price = price ?? throw new ArgumentNullException(nameof(price));<br>        Validate();<br>    }<br><br>    private void Validate()<br>    {<br>        if (ProductId.Value &lt;= 0)<br>        {<br>            throw new BusinessRuleBrokenException(&quot;Product ID must be a positive value.&quot;);<br>        }<br><br>        if (!Price.HasValue)<br>        {<br>            throw new BusinessRuleBrokenException(&quot;Price cannot be negative.&quot;);<br>        }<br>    }<br>}</pre><h4>Leveraging Modern C#: Required Properties</h4><p>As you can see in the code sample above, in our OrderItem Domain model, we utilize the required and init keywords for the Price property within our OrderItem entity. This is a deliberate design choice. In an e-commerce system, an order item without a price is a critical failure.</p><p>By using required, we move the validation from &#39;runtime&#39; to &#39;compile-time,&#39; ensuring that the compiler itself prevents the creation of an invalid OrderItem. Furthermore, using init ensures <strong>immutability</strong>; once the price is set during the checkout process, it is locked, protecting the integrity of the financial data against accidental changes later in the application lifecycle.</p><h4>Is using required properties and init setters Over-Engineering?</h4><p>As we’ve seen, setting up required properties init setters and [SetsRequiredMembers] to a simple entity adds a layer of ceremony to our code. To a developer used to &#39;Rapid Prototyping,&#39; this might feel like over-engineering. You might ask: <em>“Why not just use a public property and be done with it?”</em></p><p>The answer lies in <strong>The Cost of a Bug</strong>.</p><ul><li><strong>Without </strong><strong>required:</strong> You can accidentally create an OrderItem without a ProductId. Your code will compile, but your database will crash later with a DbUpdateException.</li><li><strong>With </strong><strong>required:</strong> The compiler stops you immediately. It forces you to fix the logic before the code even runs.</li></ul><p>However, there is a difference between <strong>complexity</strong> and <strong>complication</strong>.</p><ul><li><strong>Complicated</strong> code is a mess that is hard to follow.</li><li><strong>Complex</strong> architecture (like the one we built) uses strict rules to keep the system <strong>simple to maintain</strong>.</li></ul><blockquote>By using required members, we aren&#39;t just adding keywords; we are shifting the cost of finding bugs from our customers (at runtime) to our compilers (at dev-time). In professional e-commerce, where a single bug in a price calculation can cost thousands of dollars, this &#39;over-engineering&#39; is actually a highly efficient safety net.</blockquote><h4>Handling Framework-Generated Properties</h4><p>One challenge when using modern C# features with EF Core is handling properties like Id or ForeignKeys. The C# compiler wants us to initialize every non-nullable property, but these values are generated by the database <em>after</em> the object is created.</p><p>To solve this in OrderItem entity, we used the default! (null-forgiving) operator. This allows us to satisfy the compiler&#39;s safety checks while acknowledging that our ORM will manage the lifecycle of these identity properties. It’s a pragmatic bridge between the strictness of C# and the reality of database-driven applications.</p><blockquote><strong>The Verdict:</strong> If you are building a throwaway prototype, it’s over-engineering. But if you are building an <strong>EShopping</strong> system where an empty ProductId or a null Price means a failed transaction, these keywords are your cheapest and most effective form of Unit Testing. It’s not over-engineering; it’s <strong>static insurance</strong>.</blockquote><h3>Domain Invariants: The Maximum Price Limit</h3><p>Before we implement the Order entity, we must first define the rules that govern it. Business rules often live in documents or tickets, but in DDD, we codify them directly into the domain. The MaximumPriceLimits class is a perfect example of a <strong>Domain Invariant</strong>. We will introduce the MaximumPriceLimits class to act as a <strong>Domain Invariant</strong>. This ensures that our application enforces strict financial boundaries on every purchase, regardless of the currency used. It encapsulates the policy that restricts order totals based on currency. By centralizing this logic in domain model, we ensure that if the limits change (e.g., inflation adjustments), we only have to update one place in our code.</p><pre>namespace EShoppingTutorial.Core.Domain.InvariantRules;<br><br>public static class MaximumPriceLimits<br>{<br>    public static decimal GetMaximumPriceLimit(Currency curency) =&gt; curency switch<br>    {<br>        Currency.USD =&gt; 10_000m,<br>        Currency.EUR =&gt; 9_000m,<br>        Currency.Rial =&gt; 8_000m,<br>        _ =&gt; throw new BusinessRuleBrokenException(&quot;MoneyUnit (Currency) is not valid!&quot;)<br>    };<br>}</pre><h4>Why Maximum Price Limits class?</h4><p>You might ask, “Why do we need a specific class just to return a number?” In a real-world e-commerce system, we rarely allow unlimited purchasing power. We typically have constraints for fraud prevention, risk management, or regulatory compliance. For example, an unverified account might be limited to $10,000 per transaction. This rule is what we call a <strong>Domain Invariant</strong>. A Domain Invariant is a business rule that <strong>must always be true</strong>, no matter what. By codifying this rule inside the Domain Layer (specifically within the Order entity using the MaximumPriceLimits rule), we achieve <strong>Guaranteed Consistency</strong>.</p><p>In many junior-level applications, validation logic like “max price” is often written in the UI or the Controller. This creates a security risk: if someone calls your API directly (bypassing the UI), or if a developer writes a background job and forgets to copy-paste that validation logic, you end up with invalid data in your database.</p><p><strong>The Domain Is the Final Gatekeeper</strong> Because the Order entity itself enforces this rule, it becomes impossible to create an invalid order. It simply does not matter if the request comes from: Mobile App, Website Checkout, a Manual Admin Override or a Background Batch Process, the Order entity acts as the guardian, guaranteeing that this rule can <strong>never</strong> be broken.</p><h3>Implementing the Order: A Rich Domain Model</h3><p>Finally, we implement the <strong>Order</strong> entity within our Entities folder. It is important to distinguish this from a &quot;weak&quot; or &quot;Anemic&quot; model typically used in basic CRUD applications.</p><p>A <strong>Rich Domain Model</strong> does more than just hold data; it fuses state with behavior. It respects the principles of <strong>encapsulation</strong> and <strong>information hiding</strong> to ensure the integrity of the business logic.</p><pre>namespace EShoppingTutorial.Core.Domain.Entities;<br><br>public class Order : IAggregateRoot<br>{<br>    // This is Id generated by EF, so it&#39;s not &#39;required&#39; at creation. So we initialize with default! to silence the warning<br>    public OrderId Id { get; protected set; } = default!;<br><br>    // Mandatory inputs for creation<br>    public required CustomerId CustomerId { get; init; }<br>    public required Address ShippingAddress { get; init; }<br><br>    // Managed internally by business logic<br>    public Guid TrackingNumber { get; init; }<br>    public DateTime OrderDate { get; init; } = DateTime.UtcNow;<br>    public OrderStatus OrderStatus { get; protected set; }<br><br>    // Expose as IReadOnlyCollection to prevent external tampering<br>    private readonly List&lt;OrderItem&gt; _orderItems = [];<br>    public ICollection&lt;OrderItem&gt; OrderItems =&gt; _orderItems.AsReadOnly();<br><br>    // EF Core requires a parameterless constructor<br>    protected Order() { }<br><br>    [SetsRequiredMembers]<br>    public Order(CustomerId customerId, Address shippingAddress, IEnumerable&lt;OrderItem&gt; orderItems) : this()<br>    {<br>        ValidateCustomerId(customerId);<br>        ValidateOrderItems(orderItems);<br><br>        CustomerId = customerId;<br>        ShippingAddress = shippingAddress;<br><br>        TrackingNumber = Guid.NewGuid();<br>        OrderDate = DateTime.UtcNow;<br>        OrderStatus = OrderStatus.Created;<br><br>        AddOrderItems(orderItems);<br>    }<br><br>    public void AddOrderItem(OrderItem orderItem)<br>    {<br>        ArgumentNullException.ThrowIfNull(orderItem);<br>        ValidateMaxPriceLimit(orderItem);<br>        _orderItems.Add(orderItem);<br>    }<br><br>    public void MarkAsCancelled()<br>    {<br>        if (OrderStatus is not OrderStatus.Created)<br>        {<br>            throw new BusinessRuleBrokenException(&quot;Only orders in &#39;Created&#39; state can be cancelled.&quot;);<br>        }<br><br>        OrderStatus = OrderStatus.Cancelled;<br>    }<br><br>    public void MarkAsPending()<br>    {<br>        if (OrderStatus is not OrderStatus.Created)<br>        {<br>            throw new BusinessRuleBrokenException(&quot;Only orders in &#39;Created&#39; state can be suspended.&quot;);<br>        }<br><br>        OrderStatus = OrderStatus.Pending;<br>    }<br><br>    public void MarkAsShipped()<br>    {<br>        if (OrderStatus is not OrderStatus.Pending)<br>        {<br>            throw new BusinessRuleBrokenException($&quot;Order cannot be shipped in its current state: {OrderStatus}.&quot;);<br>        }<br><br>        OrderStatus = OrderStatus.Shipped;<br>    }<br><br>    private void AddOrderItems(IEnumerable&lt;OrderItem&gt; orderItems)<br>    {<br>        foreach (var orderItem in orderItems)<br>        {<br>            ValidateMaxPriceLimit(orderItem);<br>            _orderItems.Add(orderItem);<br>        }<br>    }<br><br>    private static void ValidateOrderItems(IEnumerable&lt;OrderItem&gt; orderItems)<br>    {<br>        if (orderItems is null || !orderItems.Any())<br>        {<br>            throw new BusinessRuleBrokenException(&quot;Order must have at least one item.&quot;);<br>        }<br>    }<br><br>    private void ValidateMaxPriceLimit(OrderItem orderItem)<br>    {<br>        var currency = orderItem.Price.Currency;<br>        var maximumPriceLimit = MaximumPriceLimits.GetMaximumPriceLimit(currency);<br>        var sumPriceOfOrderItems = _orderItems.Sum(en =&gt; en.Price.Value);<br><br>        if (sumPriceOfOrderItems + orderItem.Price.Value &gt; maximumPriceLimit)<br>        {<br>            throw new BusinessRuleBrokenException(&quot;Maximum price has been reached!&quot;);<br>        }<br>    }<br><br>    private static void ValidateCustomerId(CustomerId customerId)<br>    {<br>        if (customerId is null || customerId.Value == 0)<br>        {<br>            throw new BusinessRuleBrokenException(&quot;You must supply Customer Id!&quot;);<br>        }<br>    }<br>}</pre><p>In this architecture, the Order acts as the <strong>Aggregate Root</strong>. It serves as the single entry point for all operations concerning the order and its constituent items.</p><ul><li><strong>Controlled Access:</strong> Notice that the <strong>OrderItems</strong> are exposed as a read-only collection. This prevents external layers from bypassing the Order and manipulating the items directly.</li><li><strong>Encapsulation of Logic:</strong> By restricting the creation and modification of order items to the Order’s constructor (or specialized domain methods), we ensure that business rules — such as quantity limits or price validations — are consistently applied.</li><li><strong>Data Integrity:</strong> The Order is the guardian of its boundary. It ensures that the entire “Aggregate” (the Order plus its Items) remains in a valid state throughout its lifecycle. Instead of spreading business logic across various services, we keep it right where it belongs: inside the domain model.</li></ul><h3>Domain Services: Logic Beyond Entities — When Entities Aren’t Enough</h3><p>While our <strong>Order</strong> entity is &#39;rich&#39; with logic, it shouldn&#39;t be responsible for everything. Calculating tax is a perfect example. Tax rates change constantly and depend on external legal tables.</p><p>By creating the <strong>ITaxCalculationService</strong>, we keep our <strong>Order</strong> entity pure. The <strong>Order</strong> aggregate knows that it <em>needs</em> tax, but it shouldn&#39;t know the complex, ever-changing rules of regional tax APIs or government tables. This is an &quot;External State&quot; dependency. Since the <strong>Order Entity</strong> shouldn’t know about HTTP clients or complex tax databases, we delegate this to a <strong>Domain Service</strong>.</p><h4>1. The Domain Contract (The Interface)</h4><p>We define the service contract in the <strong>EShoppingTutorial.Core.Domain</strong> layer in the folder <strong>Services</strong>. This keeps our domain &quot;pure&quot; by defining <em>what</em> we need without worrying about <em>how</em> it&#39;s implemented.</p><pre>namespace EShoppingTutorial.Core.Domain.Services;<br><br>public interface ITaxCalculationService<br>{<br>    // We return a Task because external lookups (APIs/DBs) are asynchronous<br>    Task&lt;Price&gt; CalculateTaxAsync(Address shippingAddress, decimal orderTotal, Currency currency);<br>}</pre><h4>2. Using the ITaxCalculationService in the Order Entity</h4><p>In DDD, an entity can use a Domain Service, but it usually shouldn’t “own” it. We add the logic to the <strong>Order </strong>class. Notice that we don&#39;t put the <strong>ITaxCalculationService</strong> in the constructor; instead, we pass it into the method that needs it (Method Injection). This keeps the entity &quot;pure&quot; while allowing it to perform complex tasks. Notice how the <strong>Order </strong>maintains control over the <strong>Business Rule</strong> (tax can only be applied to new orders), while delegating the calculation.</p><p>We add the following method to our Order class:</p><pre>    public async Task ApplyTaxAsync(ITaxCalculationService taxService)<br>    {<br>        if (OrderStatus != OrderStatus.Created)<br>        {<br>            throw new BusinessRuleBrokenException(&quot;Tax can only be applied to new orders.&quot;);<br>        }<br><br>        var currentTotal = _orderItems.Sum(x =&gt; x.Price.Value);<br>        var currency = _orderItems.First().Price.Currency;<br><br>        // Delegate the complex calculation to the Domain Service<br>        var taxValue = await taxService.CalculateTaxAsync(ShippingAddress, currentTotal, currency);<br><br>        // System Product ID for Tax. The &quot;Shadow Product&quot; Approach. Create a row in your database specifically named &#39;Tax&#39; and use its real ID<br>        const int TaxProductId = 99999;<br><br>        // Add tax as a special OrderItem or update a Tax property<br>        // For this example, let&#39;s assume we add it as an order item:<br>        var taxItem = new OrderItem(<br>            productId: new ProductId(TaxProductId), // System Product ID for Tax<br>            price: taxValue<br>        );<br><br>        _orderItems.Add(taxItem);<br>    }</pre><h4>The “Shadow Product” Approach</h4><p>As you can see in the method above, we used the <strong>shadow product id</strong> for the tax entry. In many e-commerce systems, “Tax,” “Shipping,” and “Discount” are actually created as real rows in the <strong>Products </strong>table with a flag like <strong>IsSystemProduct = true</strong>.</p><p>Maybe you would fetch the ID for the “Tax” product from a configuration file and use that. <strong>The Sample Code:</strong> <strong>var taxEntry = new OrderItem(_settings.TaxProductId, taxValue);</strong></p><h4>3. The Implementation of Tax Calculation (in the Infrastructure Layer)</h4><p>Finally, we implement the interface in a separate <strong>Infrastructure</strong> project. This is where the “External State” the <strong>HttpClient</strong> and API keys live, keeping them far away from our core business logic. We need a dedicated <strong>Infrastructure Class Library</strong>. In a truly decoupled architecture, we separate our <strong>Persistence</strong> (Database) from our <strong>Infrastructure</strong> (External APIs). Mixing them can lead to “Leaky Abstractions” and bloated dependency trees.</p><ul><li><strong>Persistence</strong> is for the data we ‘own’ and control.</li><li><strong>Infrastructure</strong> is for the services we ‘consume’ (like a Tax API or an Email Gateway).</li></ul><ol><li>Right-click on your EShoppingTutorial <strong>Solution</strong> and select <strong>Add</strong> &gt; <strong>New Project</strong>.</li><li>Search for the <strong>Class Library </strong>template.</li><li>Name the project <strong>EShoppingTutorial.Infrastructure</strong> and click <strong>Create</strong>.</li><li>Create a folder called “External Services” within your infrastructure project.</li><li>Once the project is created, remember to add a <strong>Project Reference</strong> to <strong>EShoppingTutorial.Core.Domain.</strong></li><li>In the “External Services” folder, create a new class named “ExternalTaxProvider.cs”.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*Fbl9iRDIn4GwZB7VcZaZVg.png" /><figcaption>Create a new file GlobalUsings.cs at the root of your project</figcaption></figure><p>Add the following method to your ExternalTaxProvider class:</p><pre>using EShoppingTutorial.Core.Domain.Enums;<br>using EShoppingTutorial.Core.Domain.Services;<br>using EShoppingTutorial.Core.Domain.ValueObjects;<br><br>namespace EShoppingTutorial.Infrastructure.ExternalServices;<br><br>public class ExternalTaxProvider : ITaxCalculationService<br>{<br>    public async Task&lt;Price&gt; CalculateTaxAsync(Address shippingAddress, decimal orderTotal, Currency currency)<br>    {<br>        // In a real scenario, this would call an API like TaxJar or Avalara<br>        // var response = await _httpClient.GetFromJsonAsync&lt;TaxResponse&gt;(...);<br>        // For this example, we will mock the tax calculation<br><br>        decimal mockTaxRate = shippingAddress.Country.Equals(&quot;USA&quot;) ? 0.08m : 0.15m;<br><br>        var value = orderTotal * mockTaxRate;<br><br>        return new Price(value, currency);<br>    }<br>}</pre><blockquote>The ExternalTaxProvider is the concrete implementation. In a real-world enterprise application, this is where you would integrate with professional tax services like <strong>TaxJar</strong>, <strong>Avalara</strong>, or <strong>Stripe Tax</strong>.</blockquote><h4>Why this is a “Clean” implementation:</h4><ul><li><strong>The Entity stays “Blind”:</strong> The Order doesn&#39;t know about HttpClient or JSON.</li><li><strong>Testability:</strong> In your Unit Tests, you can pass a Mock&lt;ITaxCalculationService&gt; that returns a flat $10 tax, allowing you to test the Order logic without an internet connection.</li><li><strong>Flexibility:</strong> If you switch tax providers next year, you only change the Infrastructure layer; your Core Domain remains untouched.</li></ul><h3>Verification Through Unit Testing: The Benefit of Persistence Ignorance</h3><p>Because our Order entity is a <strong>Pure .NET Object (POCO)</strong> and adheres to the principle of <strong>Persistence Ignorance (PI)</strong>, it is completely decoupled from external dependencies like databases or APIs.</p><p>This isolation is a massive advantage for developers. It allows us to write lightning-fast unit tests that verify our business logic in milliseconds. Since the entity itself handles the validation and raises our custom BusinessRuleBrokenException, we can confirm that our &quot;Domain Guardrails&quot; are working exactly as intended without ever spinning up a database.</p><p>Let’s write a few unit tests to verify our Order entity&#39;s behavior and ensure our business rules are bulletproof.</p><h4>Creating the Test Suite</h4><p>To verify our domain logic, we need a dedicated project for our unit tests. We will use a standard testing framework to ensure our business rules remain intact as the application grows.</p><ol><li>Right-click on your <strong>Solution</strong> and select <strong>Add</strong> &gt; <strong>New Project</strong>.</li><li>Search for the <strong>NUnit Test Project</strong> template. (For this tutorial, we will proceed with <strong>NUnit</strong>).</li><li>Name the project <strong>EShoppingTutorial.UnitTests </strong>and click <strong>Create</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*TUBXvc_MNrpYlIgKF7njnQ.png" /><figcaption>Adding the EShoppingTutorial.UnitTests to the solution</figcaption></figure><h4>Managing Dependencies</h4><p>Once the project is created, remember to add a <strong>Project Reference</strong> to <strong>EShoppingTutorial.Core.Domain</strong>. This allows our test suite to “see” the entities and value objects we just built. To take advantage of Moq’s power in order to fake the external dependencies, we also need to install the necessary libraries. In a modern .NET environment, we aim to use the latest stable versions of the <strong>Moq</strong> nuget packages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*R3KweEkA0tD6o_U57sTyfQ.png" /><figcaption>Right-click on the Solution and select Manage NuGet Packages for Solution…</figcaption></figure><ol><li>Right-click on the <strong>Solution</strong> and select <strong>Manage NuGet Packages for Solution</strong></li><li>Navigate to the <strong>Browse</strong> tab and search for <strong>Moq </strong>nuget package.</li><li>Select the <strong>EShoppingTutorial.UnitTests</strong> project and click <strong>Install</strong>.</li></ol><h4>Organizing the Test Project</h4><p>To maintain a clean and discoverable codebase, we will mirror our Core project’s structure within the EShoppingTutorial.UnitTests project. By following this convention, any developer can instantly find the tests associated with a specific domain component and also this makes it much easier to locate tests as your application grows.</p><h4>Creating the GlobalUsings.cs File</h4><p>Create a new file at the root of your EShoppingTutorial.UnitTests project:</p><p>To keep our test project clean and maintainable, we utilize <strong>Global Using Directives</strong>. By centralizing our common namespaces — such as NUnit, MOQ, and our Domain entities — into a single GlobalUsings.cs file, we eliminate repetitive boilerplate code. This ensures that our test classes remain focused strictly on behavior and business logic, significantly improving the &#39;signal-to-noise&#39; ratio of our codebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*Cg8jmoKllhH1Hi0kfVq8Rw.png" /><figcaption>Create a new file GlobalUsings.cs at the root of your project</figcaption></figure><pre>// Standard .NET namespaces<br>global using System;<br>global using System.Linq;<br>global using System.Collections.Generic;<br>global using System.Threading.Tasks;<br><br>// Frameworks<br>global using NUnit.Framework;<br>global using Moq;<br>global using Microsoft.EntityFrameworkCore;<br><br>// Domain Specific Namespaces<br>global using EShoppingTutorial.Core.Domain.Entities;<br>global using EShoppingTutorial.Core.Domain.Enums;<br>global using EShoppingTutorial.Core.Domain.ValueObjects;<br>global using SharedKernel.Exceptions;<br>global using EShoppingTutorial.Core.Persistence;<br>global using EShoppingTutorial.Core.Persistence.Repositories;<br>global using EShoppingTutorial.Core.Domain.Services;</pre><h4>Creating the Order Unit Tests</h4><ol><li>Inside your Unit Test project, create the following folder hierarchy: <strong>Domain</strong> &gt; <strong>Entities</strong></li><li>Add a new class file named <strong>OrderUnitTests.cs</strong> inside the Entities folder.</li></ol><p><strong>OrderUnitTests</strong> class will be dedicated exclusively to verifying the business logic and invariants of the Order aggregate root.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*yHgE-1wwPyu7rAj4hTNpYQ.png" /><figcaption>Creating the OrderUnitTests.cs File</figcaption></figure><pre>namespace EShoppingTutorial.UnitTests.Domain.Entities;<br><br>[TestFixture]<br>public class OrderUnitTests<br>{<br>    [Test]<br>    public void InstantiatingOrder_WithEmptyOrderItems_ExpectsBusinessRuleBrokenException()<br>    {<br>        // arrange &amp; act<br>        static void testDelegate() =&gt; new Order(new CustomerId(1), Mock.Of&lt;Address&gt;(), orderItems: []);<br><br>        // assert<br>        var ex = Assert.Throws&lt;BusinessRuleBrokenException&gt;(testDelegate);<br>        Assert.That(ex.Message.Contains(&quot;Order must have at least one item&quot;, StringComparison.CurrentCultureIgnoreCase));<br>    }<br><br>    [Test]<br>    public void OrderItemsProperty_AddingOrderItemToReadOnlyCollection_ExpectsNotSupportedException()<br>    {<br>        // arrange<br>        var productIdMock = new ProductId(1);<br>        var priceMock = new Price(1, Currency.USD);<br>        var orderItemMock = new OrderItem(productIdMock, priceMock);<br><br>        var order = new Order(new CustomerId(1), Mock.Of&lt;Address&gt;(), [orderItemMock]);<br><br>        // act<br>        void testDelegate() =&gt; order.OrderItems.Add(orderItemMock);<br><br>        // assert<br>        var ex = Assert.Throws&lt;NotSupportedException&gt;(testDelegate);<br>        Assert.That(ex.Message.Contains(&quot;Collection is read-only&quot;, StringComparison.CurrentCultureIgnoreCase));<br>    }<br><br>    [Test]<br>    public void AddOrderItem_ShouldThrowException_WhenPriceExceedsLimit()<br>    {<br>        // 1. Arrange: Setup our entities and a price that exceeds the USD limit ($10,000)<br>        var customerId = new CustomerId(1);<br><br>        // To directly test the AddOrderItem method, we mock the initialization step of the Order class.<br>        var order = Mock.Of&lt;Order&gt;(); <br><br>        var expensivePrice = new Price(11000m, Currency.USD);<br>        var productId = new ProductId(99);<br>        var orderItem = new OrderItem(productId, expensivePrice);<br><br>        // 2. Act &amp; 3. Assert: Verify the exception is thrown with the correct message<br>        var ex = Assert.Throws&lt;BusinessRuleBrokenException&gt;(() =&gt; order.AddOrderItem(orderItem));<br><br>        Assert.That(ex.Message, Does.Contain(&quot;Maximum price has been reached&quot;));<br>    }<br><br>    [TestCase(OrderStatus.Pending)]<br>    public void MarkAsShipped_ShouldSetStatusToShipped_WhenOrderIsPending(OrderStatus initialStatus)<br>    {<br>        // Arrange<br>        var order = Mock.Of&lt;Order&gt;(x =&gt; x.OrderStatus == initialStatus); // To directly test the MarkAsShipped method, we mock the initialization step of the Order class.<br><br>        // Act<br>        order.MarkAsShipped();<br><br>        // Assert<br>        Assert.That(order.OrderStatus, Is.EqualTo(OrderStatus.Shipped));<br>    }<br><br>    [TestCase(OrderStatus.Shipped)]<br>    [TestCase(OrderStatus.Delivered)]<br>    [TestCase(OrderStatus.Cancelled)]<br>    public void MarkAsShipped_ShouldThrowException_WhenOrderIsNotCreatedOrPendingState(OrderStatus initialStatus)<br>    {<br>        // Arrange<br>        var order = Mock.Of&lt;Order&gt;(x =&gt; x.OrderStatus == initialStatus); // To directly test the MarkAsShipped method, we mock the initialization step of the Order class.<br><br>        // Act &amp; Assert<br>        var ex = Assert.Throws&lt;BusinessRuleBrokenException&gt;(order.MarkAsShipped);<br>        Assert.That(ex.Message.Contains(&quot;Order cannot be shipped&quot;, StringComparison.CurrentCultureIgnoreCase));<br>    }<br><br>    [Test]<br>    public void AddOrderItem_ShouldAddItem_WhenValid()<br>    {<br>        // Arrange<br>        var order = Mock.Of&lt;Order&gt;(); // To directly test the AddOrderItem method, we mock the initialization step of the Order class.<br>        var productId = new ProductId(1);<br>        var orderItem = new OrderItem(productId, new Price(100, Currency.EUR));<br><br>        // Act<br>        order.AddOrderItem(orderItem);<br><br>        // Assert<br>        Assert.That(order.OrderItems, Contains.Item(orderItem));<br>    }<br><br>    [Test]<br>    public void AddOrderItem_ShouldThrowException_WhenExceedingMaxPrice()<br>    {<br>        // Arrange<br>        var order = Mock.Of&lt;Order&gt;(); // To directly test the AddOrderItem method, we mock the initialization step of the Order class.<br>        var productId = new ProductId(1);<br><br>        // Assume the max price for Euro is 9000 for this test<br>        var expensiveItem = new OrderItem(productId, new Price(15000, Currency.EUR));<br><br>        // Act &amp; Assert<br>        var ex = Assert.Throws&lt;BusinessRuleBrokenException&gt;(() =&gt; order.AddOrderItem(expensiveItem));<br>        Assert.That(ex.Message.Contains(&quot;Maximum price has been reached&quot;, StringComparison.CurrentCultureIgnoreCase));<br>    }<br><br>    [Test]<br>    public void MarkAsCancelled_ShouldSetStatusToCancelled_WhenOrderIsCreatedOrPending()<br>    {<br>        // Arrange<br>        var order = Mock.Of&lt;Order&gt;(x =&gt; x.OrderStatus == OrderStatus.Created); // To directly test the MarkAsCancelled method, we mock the initialization step of the Order class.<br><br>        // Act<br>        order.MarkAsCancelled();<br><br>        // Assert<br>        Assert.That(order.OrderStatus, Is.EqualTo(OrderStatus.Cancelled));<br>    }<br><br>    [TestCase(OrderStatus.Shipped)]<br>    [TestCase(OrderStatus.Delivered)]<br>    [TestCase(OrderStatus.Cancelled)]<br>    [TestCase(OrderStatus.Pending)]<br>    public void MarkAsCancelled_ShouldThrowException_WhenOrderIsNotCreatedState(OrderStatus initialStatus)<br>    {<br>        // Arrange<br>        var order = Mock.Of&lt;Order&gt;(x =&gt; x.OrderStatus == initialStatus); // To directly test the MarkAsCancelled method, we mock the initialization step of the Order class.<br><br>        // Act &amp; Assert<br>        var ex = Assert.Throws&lt;BusinessRuleBrokenException&gt;(order.MarkAsCancelled);<br>        Assert.That(ex.Message.Contains(&quot;Only orders in &#39;Created&#39; state can be cancelled&quot;, StringComparison.CurrentCultureIgnoreCase));<br>    }<br><br>    [TestCase(OrderStatus.Shipped)]<br>    [TestCase(OrderStatus.Delivered)]<br>    [TestCase(OrderStatus.Cancelled)]<br>    [TestCase(OrderStatus.Pending)]<br>    public void MarkAsSuspended_ShouldThrowException_WhenOrderIsNotCreatedState(OrderStatus initialStatus)<br>    {<br>        // Arrange<br>        var order = Mock.Of&lt;Order&gt;(x =&gt; x.OrderStatus == initialStatus); // To directly test the MarkAsPending method, we mock the initialization step of the Order class.<br><br>        // Act &amp; Assert<br>        var ex = Assert.Throws&lt;BusinessRuleBrokenException&gt;(order.MarkAsPending);<br>        Assert.That(ex.Message.Contains(&quot;Only orders in &#39;Created&#39; state can be suspended&quot;, StringComparison.CurrentCultureIgnoreCase));<br>    }<br>}</pre><h4>Creating the OrderApplyTax Unit Tests</h4><ol><li>Inside your Unit Test project, create the following folder hierarchy: <strong>Domain</strong> &gt; <strong>Entities</strong></li><li>Add a new class file named <strong>OrderApplyTaxUnitTests.cs</strong> inside the <strong>Entities</strong> folder.</li></ol><p><strong>OrderApplyTaxUnitTests</strong> class will be dedicated exclusively to verifying the business logic of the aggregate root Order ApplyTaxAsync() method.</p><pre>namespace EShoppingTutorial.UnitTests.Domain;<br><br>[TestFixture]<br>public class OrderApplyTaxUnitTests<br>{<br>    private Mock&lt;ITaxCalculationService&gt; _taxServiceMock;<br><br>    [SetUp]<br>    public void Setup()<br>    {<br>        _taxServiceMock = new Mock&lt;ITaxCalculationService&gt;();<br>    }<br><br>    [Test]<br>    public async Task ApplyTaxAsync_ShouldAddTaxItem_WhenOrderIsCreated()<br>    {<br>        // Arrange<br>        var customerId = new CustomerId(1);<br>        var address = new Address(&quot;123 Tech St&quot;, &quot;New York&quot;, &quot;USA&quot;, &quot;10001&quot;);<br>        var items = new List&lt;OrderItem&gt;<br>        {<br>            new OrderItem(new ProductId(1), new Price(100, Currency.USD))<br>        };<br><br>        var order = new Order(customerId, address, items);<br><br>        var expectedTax = new Price(10, Currency.USD);<br><br>        // Setup the mock to return 10 USD tax<br>        _taxServiceMock<br>            .Setup(s =&gt; s.CalculateTaxAsync(address, 100, Currency.USD))<br>            .ReturnsAsync(expectedTax);<br><br>        // Act<br>        await order.ApplyTaxAsync(_taxServiceMock.Object);<br><br>        // Assert<br>        Assert.That(order.OrderItems.Count, Is.EqualTo(2)); // Original item + Tax item<br><br>        var taxItem = order.OrderItems.FirstOrDefault(x =&gt; x.ProductId.Value == 99999);<br>        Assert.That(taxItem, Is.Not.Null);<br>        Assert.That(taxItem.Price.Value, Is.EqualTo(10));<br><br>        // Verify the service was actually called once<br>        _taxServiceMock.Verify(s =&gt; s.CalculateTaxAsync(address, 100, Currency.USD), Times.Once);<br>    }<br><br>    [Test]<br>    public void ApplyTaxAsync_ShouldThrowException_WhenOrderIsNotInCreatedState()<br>    {<br>        // Arrange<br>        var customerId = new CustomerId(1);<br>        var address = new Address(&quot;123 Tech St&quot;, &quot;New York&quot;, &quot;USA&quot;, &quot;10001&quot;);<br>        var items = new List&lt;OrderItem&gt;<br>        {<br>            new OrderItem(new ProductId(1), new Price (100, Currency.USD))<br>        };<br><br>        var order = new Order(customerId, address, items);<br><br>        // Manually move state to Pending in order to simulate non-created state<br>        order.MarkAsPending();<br><br>        // Act &amp; Assert<br>        var ex = Assert.ThrowsAsync&lt;BusinessRuleBrokenException&gt;(async () =&gt; await order.ApplyTaxAsync(_taxServiceMock.Object));<br><br>        Assert.That(ex.Message, Is.EqualTo(&quot;Tax can only be applied to new orders.&quot;));<br>    }<br>}</pre><h4>Why Mocking the Domain Service is Key</h4><p>Notice that our unit test doesn’t need an internet connection or a real Tax API. By using <strong>Moq</strong>, we provide a ‘fake’ version of the ITaxCalculationService that returns exactly what we want.</p><p>This allows us to test the <strong>internal logic of the Order entity</strong> (like checking the OrderStatus and adding the tax item to the collection) in milliseconds. This is the power of the Domain Service pattern: we decouple the <strong>business rule</strong> from the <strong>technical implementation</strong>.</p><blockquote>We have also written more unit tests for the value objects and the repository layer. Those interested can check out the source code on GitHub: <strong>→ </strong><a href="https://github.com/tomajexpress/Domain.Driven.Implementation.In.CSharp.NET.Core.git"><strong>Download Source Code from GitHub</strong></a></blockquote><h3>Persistence: Mapping Domain Models to the Database</h3><p>So far, our architecture has served us well. We have successfully verified our business rules and invariants using isolated unit tests — all without needing an external database. This is the power of <strong>Persistence Ignorance</strong>.</p><p>However, for our application to be useful, we must eventually persist these entities. To do this, we will use <strong>Entity Framework Core (EF Core)</strong> and the <strong>Code-First Fluent API</strong> approach. Instead of manually writing SQL scripts, we will define how our C# classes map to database tables and use <strong>EF Core Migrations</strong> to generate our schema.</p><h4>The Role of Fluent API Configurations</h4><p>In Clean Architecture, we want to keep our Domain entities “clean.” This means we avoid using Data Annotations (like [Key] or [Required]) inside our entity classes. Instead, we use <strong>Mapping Configuration</strong> classes. This separates our database schema concerns from our business logic.</p><p>We will start by creating a Mappings folder inside Core.Persistence project, we will implement <strong>OrderConfiguration</strong> and <strong>OrderItemConfiguration</strong> to define exactly how our Rich Domain Model—including our Value Objects and Strongly Typed IDs—should be stored in the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*mnQwrRrWLGUx4qYGkCGi9A.png" /><figcaption>A folder named “Mappings” is created in the “Core.Persistence” project, containing the files OrderConfiguration and OrderItemConfiguration</figcaption></figure><h4>Implementing <strong>OrderConfiguration</strong>: Bridging Domain and Database</h4><p>In our <strong>OrderConfiguration</strong>, we use the IEntityTypeConfiguration&lt;Order&gt; interface to keep our mapping logic separate from our domain model. This ensures our Order entity remains a <strong>POCO</strong> (Plain Old CLR Object) and doesn&#39;t know anything about tables or columns.</p><pre>using Microsoft.EntityFrameworkCore;<br>using Microsoft.EntityFrameworkCore.Metadata.Builders;<br><br>namespace EShoppingTutorial.Core.Persistence.Mappings;<br><br>public class OrderConfiguration : IEntityTypeConfiguration&lt;Order&gt;<br>{<br>    public void Configure(EntityTypeBuilder&lt;Order&gt; builder)<br>    {<br>        builder.ToTable(&quot;Orders&quot;);<br><br>        builder.HasKey(o =&gt; o.Id);<br><br>        builder.Property(o =&gt; o.Id).HasConversion(<br>            id =&gt; id.Value,<br>            value =&gt; new OrderId(value));<br><br>        builder.Property(o =&gt; o.Id).ValueGeneratedOnAdd().HasColumnName(&quot;Id&quot;);<br><br>        builder.Property(o =&gt; o.TrackingNumber).HasColumnName(&quot;TrackingNumber&quot;).IsRequired();<br><br>        builder.HasIndex(o =&gt; o.TrackingNumber).IsUnique();<br><br>        builder.OwnsOne(o =&gt; o.ShippingAddress, a =&gt;<br>        {<br>            a.Property(p =&gt; p.Street).HasColumnName(&quot;Street&quot;).HasMaxLength(100).IsRequired();<br>            a.Property(p =&gt; p.City).HasColumnName(&quot;City&quot;).HasMaxLength(50).IsRequired();<br>            a.Property(p =&gt; p.Country).HasColumnName(&quot;Country&quot;).HasMaxLength(50).IsRequired();<br>            a.Property(p =&gt; p.ZipCode).HasColumnName(&quot;ZipCode&quot;).HasMaxLength(10).IsRequired();<br>        });<br><br>        builder.Property(o =&gt; o.OrderDate).HasColumnName(&quot;OrderDate&quot;).HasMaxLength(10).IsRequired();<br><br>        builder.Property(o =&gt; o.CustomerId).HasColumnName(&quot;CustomerId&quot;).IsRequired();<br><br>        builder.Property(o =&gt; o.CustomerId).HasConversion(<br>            id =&gt; id.Value,<br>            value =&gt; new CustomerId(value));<br><br>        builder.Property(o =&gt; o.OrderStatus).HasColumnName(&quot;OrderStatus&quot;).IsRequired();<br><br>        builder.HasMany(o =&gt; o.OrderItems)<br>               .WithOne()<br>               .HasForeignKey(x=&gt; x.OrderId)<br>               .IsRequired()<br>               .OnDelete(DeleteBehavior.Cascade);<br>    }<br>}</pre><h4>Mapping the Child Entity: OrderItemConfiguration</h4><p>Now that we’ve mapped the Aggregate Root, we need to configure the OrderItem. The most interesting part of this configuration is how we handle the Price Value Object.</p><p>In Domain-Driven Design, a Value Object doesn’t have its own identity; it belongs to its parent. In Entity Framework Core, we represent this using the <strong>Owned Entity Type</strong> pattern. By calling builder.OwnsOne(o =&gt; o.Price), we tell EF Core to &quot;flatten&quot; the Value and Currency properties directly into the OrderItems table rather than creating a separate table for prices.</p><pre>using Microsoft.EntityFrameworkCore;<br>using Microsoft.EntityFrameworkCore.Metadata.Builders;<br><br>namespace EShoppingTutorial.Core.Persistence.Mappings;<br><br>public class OrderItemConfiguration : IEntityTypeConfiguration&lt;OrderItem&gt;<br>{<br>    public void Configure(EntityTypeBuilder&lt;OrderItem&gt; builder)<br>    {<br>        builder.ToTable(&quot;OrderItems&quot;);<br><br>        builder.HasKey(o =&gt; o.Id);<br><br>        builder.Property(o =&gt; o.Id)<br>            .HasConversion(<br>                id =&gt; id.Value,<br>                value =&gt; new OrderItemId(value));<br><br>        builder.Property(o =&gt; o.Id).ValueGeneratedOnAdd().HasColumnName(&quot;Id&quot;);<br><br>        builder.Property(o =&gt; o.ProductId).HasColumnName(&quot;ProductId&quot;).IsRequired();<br><br>        builder.Property(o =&gt; o.ProductId).HasConversion(<br>            id =&gt; id.Value,<br>            value =&gt; new ProductId(value));<br><br>        builder.OwnsOne(o =&gt; o.Price, price =&gt;<br>        {<br>            price.Property(x =&gt; x.Value).HasColumnName(&quot;Price_Value&quot;);<br><br>            price.Property(x =&gt; x.Currency).HasColumnName(&quot;Price_Currency&quot;);<br>        });<br><br>        // Configure OrderId as foreign key<br>        builder.Property(x =&gt; x.OrderId)<br>            .HasConversion(<br>                id =&gt; id.Value,<br>                value =&gt; new OrderId(value));<br>    }<br>}</pre><h3>The Mapping Dilemma: Why Not Just Use Conventions?</h3><p>By default, Entity Framework’s “Code-First” approach is incredibly convenient. It can automatically generate your database tables and columns based on the names of your DbSet properties. So, why do we go through the &quot;extra work&quot; of creating separate mapping files?</p><p>It’s a fair question, but the answer lies in the difference between a <strong>prototype</strong> and an <strong>enterprise-grade system</strong>.</p><h4>1. Decoupling the Domain from the Database</h4><p>If you rely solely on conventions, your database becomes a mirror image of your C# code. This creates a “tight coupling” that can become a nightmare during refactoring. Imagine you want to rename a property in your Order entity to better reflect a new business requirement. Without separate mappings, that simple C# rename <strong>forces</strong> a database migration to rename the column.</p><p>By using separate mapping files, you gain the freedom to have a property named Status in your code while the database column remains order_status_id. Your code stays clean, and your database remains stable.</p><h4>2. Enforcing Clean Architecture Principles</h4><p>In Clean Architecture, we strive for <strong>Persistence Ignorance</strong>. Our Domain entities shouldn’t care how they are stored. If we use Data Annotations (like [Key] or [Required]) directly on our entities, we are &quot;polluting&quot; our stable core with database concerns. Moving these configurations to separate mapping files keeps our entities pure and focused strictly on business logic.</p><h4>3. Advanced Configuration Control</h4><p>Separate mapping files allow you to utilize the full power of the <strong>Fluent API</strong>. This gives you control over things conventions can’t handle easily, such as:</p><ul><li>Defining complex relationships (Many-to-Many).</li><li>Configuring <strong>Value Objects</strong> (like our Price record) as Owned Types.</li><li>Setting specific SQL data types, constraints, and indexes for performance optimization.</li></ul><blockquote>“<strong>Separating your mappings:</strong> isn’t just about ‘doing extra work’ — it’s about building a firewall between your Business Logic and your Data Storage. It ensures that a change in your database technology or schema doesn’t force a rewrite of your core domain rules”</blockquote><h3>The Persistence Gateway: EShoppingTutorial DbContext</h3><p>With our mapping configurations defined, we now need a central hub to coordinate with the database. We will create the EShoppingTutorialDbContext in the root of the Core.Persistence folder.</p><p>In a growing application, manually registering dozens of mapping files inside OnModelCreating can become tedious and error-prone. To solve this, as you see in the code below, we use ApplyConfigurationsFromAssembly. This powerful method scans our current assembly for any class implementing IEntityTypeConfiguration and registers them automatically. This ensures that as we add new entities in the future, our DbContext remains lean and maintenance-free.</p><pre>using Microsoft.EntityFrameworkCore;<br>using System.Reflection;<br><br>namespace EShoppingTutorial.Core.Persistence;<br><br>public class EShoppingTutorialDbContext(DbContextOptions&lt;EShoppingTutorialDbContext&gt; dbContextOptions) : DbContext(dbContextOptions)<br>{<br>    public virtual DbSet&lt;Order&gt; Orders { get; set; }<br><br>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        //Scans a given assembly for all types that implement IEntityTypeConfiguration, and registers each one automatically<br>        modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());<br><br>        base.OnModelCreating(modelBuilder);<br>    }<br>}</pre><h3>The Order Repository: Specializing Persistence for the Aggregate Root</h3><p>While a <strong>Generic Repository</strong> provides a solid foundation for standard CRUD operations, complex <strong>Aggregate Roots</strong> often require specialized handling. In our case, an Order is never truly complete without its OrderItems.</p><p>If we relied solely on a generic implementation, we might end up with “Anemic” data — orders without order items. By creating a dedicated OrderRepository, we can specialize our queries to ensure the entire Aggregate boundary is respected, while still inheriting all the &quot;free&quot; functionality from our generic base.</p><h4>Why specialization matters in Clean Architecture:</h4><ul><li><strong>Eager Loading:</strong> We use this layer to ensure that child entities (like OrderItems) are always included in the query, preventing NullReferenceExceptions in our business logic.</li><li><strong>Ubiquitous Language:</strong> Instead of generic names like GetById, we can add methods like GetOrderWithDetailsAsync that reflect the actual needs of our use cases.</li><li><strong>Adherence to DIP:</strong> By defining an IOrderRepository in the Core layer and implementing it in the Persistence layer, we satisfy the <strong>Dependency Inversion Principle</strong>, keeping our Domain independent of EF Core details.</li></ul><pre>using GenericRepositoryEntityFramework;<br><br>namespace EShoppingTutorial.Core.Domain.Repositories;<br><br>public interface IOrderRepository : IRepository&lt;Order&gt;<br>{<br>    Task&lt;Order?&gt; GetOrderWithItemsAsync(OrderId id);<br><br>    Task&lt;IEnumerable&lt;Order&gt;&gt; GetOrdersByCustomerIdAsync(CustomerId customerId);<br>}</pre><pre>using GenericRepositoryEntityFramework;<br>using Microsoft.EntityFrameworkCore;<br><br>namespace EShoppingTutorial.Core.Persistence.Repositories;<br><br>internal class OrderRepository(EShoppingTutorialDbContext context) : Repository&lt;Order&gt;(context), IOrderRepository<br>{<br>    public EShoppingTutorialDbContext EShoppingTutorialDbContext<br>    {<br>        get { return Context as EShoppingTutorialDbContext; }<br>    }<br><br>    public async Task&lt;Order?&gt; GetOrderWithItemsAsync(OrderId id)<br>    {<br>        return await context.Orders<br>            .Include(o =&gt; o.OrderItems) <br>            .FirstOrDefaultAsync(o =&gt; o.Id == id);<br>    }<br><br>    public async Task&lt;IEnumerable&lt;Order&gt;&gt; GetOrdersByCustomerIdAsync(CustomerId customerId)<br>    {<br>        return await context.Orders<br>            .Where(o =&gt; o.CustomerId == customerId)<br>            .OrderByDescending(o =&gt; o.OrderDate)<br>            .ToListAsync();<br>    }<br>}</pre><p>Notice the use of <strong>Eager Loading</strong> via the .Include() method. Because Order is our <strong>Aggregate Root</strong>, it is responsible for the consistency of its OrderItems. By ensuring they are loaded together in the repository, we prevent the &#39;Anemic Domain Model&#39; problem where an order might be processed without its contents. Furthermore, by using our custom OrderId and CustomerId value objects in the method signatures, we make it impossible to accidentally query an order using a product ID.</p><h4><strong>Advanced Encapsulation: The Internal Repository Pattern</strong></h4><p>In this implementation, we made the OrderRepository class internal. This is a deliberate design choice. By doing this, we prevent the Application layer from instantiating or injecting repositories directly. Instead, the UnitOfWork acts as a <strong>Gateway</strong>. It &#39;owns&#39; the repositories and ensures that all data operations happen within the same DbContext lifecycle. This guarantees that when we call CompleteAsync(), every change made across multiple repositories is committed or rolled back as a single transaction.</p><h3>Ensuring Atomic Transactions: The Unit of Work Pattern</h3><p>While repositories handle data access for individual aggregates, we often face scenarios that involve multiple entities. To ensure data integrity, we need to guarantee that all changes occur within a single transaction. This is the core purpose of the <strong>Unit of Work</strong> pattern.</p><p>By implementing IUnitOfWork, we achieve two major goals:</p><ol><li><strong>Atomicity:</strong> All changes are committed to the database at once using a single SaveChangesAsync() call.</li><li><strong>Cleaner Dependency Injection:</strong> Instead of injecting five different repositories into an Application Service, we inject a single IUnitOfWork, which acts as a gateway to all repositories.</li></ol><h4>1. The Abstraction (Domain Layer): IUnitOfWork Interface</h4><p>Following the <strong>Dependency Inversion Principle</strong>, we define our interface in the root directory of the <strong>Core.Domain</strong> layer. This keeps our business logic decoupled from the specific persistence framework (EF Core).</p><pre>namespace EShoppingTutorial.Core.Domain;<br><br>public interface IUnitOfWork<br>{<br>    // The interface exposes the Repository contract, but not the internal implementation.<br>    IOrderRepository OrderRepository { get; }<br><br>    Task&lt;int&gt; CompleteAsync();<br>    Task&lt;int&gt; CompleteAsync(CancellationToken cancellationToken);<br>}</pre><h4>2. The Implementation (Persistence Layer): UnitOfWork Implementation</h4><p>The implementation resides in the <strong>Core.Persistence</strong> layer. Here, we wrap our DbContext and provide a concrete instance of our repositories. We also implement IAsyncDisposable to ensure the database context is correctly released after the operation is complete.</p><pre>namespace EShoppingTutorial.Core.Persistence;<br><br>public class UnitOfWork : IUnitOfWork, IAsyncDisposable<br>{<br>    private readonly EShoppingTutorialDbContext _context;<br><br>    // Lazy holders for our repositories<br>    private readonly Lazy&lt;IOrderRepository&gt; _orderRepository;<br><br>    public IOrderRepository OrderRepository =&gt; _orderRepository.Value;<br><br>    public UnitOfWork(EShoppingTutorialDbContext context)<br>    {<br>        _context = context ?? throw new ArgumentNullException(nameof(context));<br><br>        // Define how to create the repository, but don&#39;t create it yet<br>        _orderRepository = new Lazy&lt;IOrderRepository&gt;(() =&gt; new OrderRepository(_context));<br>    }<br><br>    public async Task&lt;int&gt; CompleteAsync()<br>    {<br>        return await _context.SaveChangesAsync().ConfigureAwait(false);<br>    }<br><br>    public async Task&lt;int&gt; CompleteAsync(CancellationToken cancellationToken)<br>    {<br>        return await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);<br>    }<br><br>    public ValueTask DisposeAsync()<br>    {<br>        return _context.DisposeAsync();<br>    }<br>}</pre><p>As you can see, the Unit of Work is not overly complex, yet it provides immense value. It acts as a C<strong>reational Placeholder</strong> for our repositories, preventing ‘Constructor Bloat’ in our Application layer. More importantly, it centralizes the CompleteAsync method. This means your Application Services don&#39;t call &#39;Save&#39; on a repository; they call &#39;Complete&#39; on the <strong>Unit of Work</strong> once the entire business transaction is ready to be finalized. This design makes the application much easier to maintain and ensures your database always remains in a consistent state.</p><h4>Optimization: Lazy Loading Repositories</h4><p>In a large system, our UnitOfWork might manage dozens of repositories. If every repository is instantiated in the constructor, you waste resources every time you resolve a UnitOfWork for a simple operation. By using the <strong>C# </strong><strong>Lazy&lt;T&gt; keyword</strong>, we defer the creation of the OrderRepository until the very moment it is called in code (unitOfWork.OrderRepository.Add(..)). Furthermore, by keeping the Repository implementation internal, we ensure that the rest of our application interacts only with the UnitOfWork and the high-level Interfaces, maintaining a clean separation of concerns.</p><h3>Building the Application Service Layer: Orchestrating Use Cases with MediatR</h3><p>In Clean Architecture the <strong>Application Service Layer</strong>, acts as the orchestrator. It doesn’t contain business rules (those live in the Domain), and it doesn’t know about database connections (those live in Persistence). Instead, it acts as a conductor, receiving a request, fetching the necessary entities, and telling them to execute their logic.</p><h4>Creating the Application Service <strong>Class Library</strong></h4><p>We need a dedicated Class Library project for our application services.</p><ol><li>Right-click on your EShoppingTutorial <strong>Solution</strong> and select <strong>Add</strong> &gt; <strong>New Project</strong>.</li><li>Search for the <strong>Class Library </strong>template.</li><li>Name the project <strong>EShoppingTutorial.Core.Application</strong> and click <strong>Create</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*o37jGHtAakTiyfU8fkilWQ.png" /><figcaption>Creating the Application Service Class Library</figcaption></figure><p>Once the project is created, remember to add a <strong>Project Reference</strong> to Core.Domain.</p><ol><li>Right-click on the <strong>Solution</strong> and select <strong>Manage NuGet Packages for Solution</strong></li><li>Navigate to the <strong>Browse</strong> tab and search for <strong>MediatR, AutoMapper, FluentValidation, FluentValidation.DependencyInjectionExtensions</strong></li><li>Select the <strong>EShoppingTutorial.Core.Application</strong> project and click <strong>Install</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*MGXp_aIvhFfggf-kAXVTCA.png" /><figcaption>Navigate to the Browse tab and search for MediatR</figcaption></figure><h4>Division of Actions into Folders</h4><p>As you see below we separate our operations into folders <strong>Commands</strong> (actions that change data) and <strong>Queries</strong> (actions that read data). We define a specific “Intent” for each action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*d-pW_8uxJKkABxUPgXryBg.png" /><figcaption><strong>EShoppingTutorial.Core.Application Structure</strong></figcaption></figure><h4>1. Creating the GlobalUsings.cs File</h4><p>Create a new file at the root of your Core.Applicationproject. To keep our project clean and maintainable, we utilize <strong>Global Using Directives</strong>.</p><pre>global using System.Reflection;<br><br>// Frameworks<br>global using MediatR;<br>global using AutoMapper;<br>global using FluentValidation;<br>global using Microsoft.Extensions.DependencyInjection;<br><br>// Domain Specific Namespaces<br>global using SharedKernel.Models;<br>global using EShoppingTutorial.Core.Domain;<br>global using EShoppingTutorial.Core.Domain.Entities;<br>global using EShoppingTutorial.Core.Domain.ValueObjects;<br>global using EShoppingTutorial.Core.Domain.Services;<br>global using EShoppingTutorial.Core.Domain.Enums;<br>global using EShoppingTutorial.Core.Application.Orders.Commands.CreateOrder;<br>global using EShoppingTutorial.Core.Application.Orders.Queries;<br>global using EShoppingTutorial.Core.Application.Common;<br>global using EShoppingTutorial.Core.Application.Orders;</pre><h4>2. The Create Action (Command)</h4><p>It brings together the <strong>Constructor</strong>, the <strong>Domain Service</strong>, and the <strong>Repository</strong>. The request arrives as a CreateOrderCommand. The ValidationBehavior intercepts the command and checks the CreateOrderCommandValidator. If the check fails, an exception is thrown before the handler is called. Within the CreateOrderCommandHandler, we transform the DTO into a rich domain entity.</p><ul><li><strong>Business Rules:</strong> The Order entity enforces that tax is only applied in the Created state.</li><li><strong>External Integration:</strong> The ITaxCalculationService handles the &quot;dirty&quot; work of external data.</li><li><strong>Persistence:</strong> The IUnitOfWork ensures that the order and its items are saved as a single atomic transaction.</li></ul><p>Add the codes below into the “CreateOrder” folder.</p><pre>namespace EShoppingTutorial.Core.Application.Orders.Commands.CreateOrder;<br><br>public record CreateOrderCommand(<br>    int CustomerId,<br>    string Street,<br>    string City,<br>    string Country,<br>    string ZipCode,<br>    List&lt;OrderItemDto&gt; Items) : IRequest&lt;int&gt;;<br><br>public record OrderItemDto(<br>    int ProductId,<br>    decimal Value,<br>    string Currency);</pre><pre>namespace EShoppingTutorial.Core.Application.Orders.Commands.CreateOrder;<br><br>internal class CreateOrderHandler(IUnitOfWork unitOfWork, <br>            ITaxCalculationService taxCalculationService,<br>            IMapper mapper) <br>            : IRequestHandler&lt;CreateOrderCommand, int&gt;<br>{<br>    public async Task&lt;int&gt; Handle(CreateOrderCommand request, CancellationToken cancellationToken)<br>    {<br>        // The handler executes the logic of the domain service and coordinates the asynchronous tax calculation.<br><br>        var items = mapper.Map&lt;List&lt;OrderItem&gt;&gt;(request.Items);<br><br>        var order = new Order(<br>            new CustomerId(request.CustomerId),<br>            new Address(request.Street, request.City, request.Country, request.ZipCode),<br>            items<br>        );<br><br>        // This is where the &#39;External State&#39; dependency is handled<br>        await order.ApplyTaxAsync(taxCalculationService);<br><br>        unitOfWork.OrderRepository.Add(order);<br><br>        await unitOfWork.CompleteAsync(cancellationToken).ConfigureAwait(false);<br><br>        return order.Id.Value;<br>    }<br>}</pre><pre>namespace EShoppingTutorial.Core.Application.Orders.Commands.CreateOrder;<br><br>public class CreateOrderCommandValidator : AbstractValidator&lt;CreateOrderCommand&gt;<br>{<br>    public CreateOrderCommandValidator()<br>    {<br>        RuleFor(x =&gt; x.CustomerId)<br>            .GreaterThan(0).WithMessage(&quot;Please enter a valid customer id!&quot;);<br><br>        // Address Component Validations<br>        RuleFor(x =&gt; x.Street)<br>            .NotEmpty().WithMessage(&quot;Street address is required.&quot;)<br>            .NotEqual(&quot;string&quot;)<br>            .MaximumLength(100);<br><br>        RuleFor(x =&gt; x.City)<br>            .NotEmpty().WithMessage(&quot;City is required.&quot;)<br>            .NotEqual(&quot;string&quot;)<br>            .MaximumLength(50);<br><br>        RuleFor(x =&gt; x.Country)<br>            .NotEmpty().WithMessage(&quot;Country is required.&quot;)<br>            .NotEqual(&quot;string&quot;)<br>            .MaximumLength(50);<br><br>        RuleFor(x =&gt; x.ZipCode)<br>            .NotEmpty().WithMessage(&quot;Zip Code is required.&quot;)<br>            .NotEqual(&quot;string&quot;);<br><br>        // Order Items Validation<br>        RuleFor(x =&gt; x.Items)<br>            .NotEmpty().WithMessage(&quot;Please enter order items!&quot;);<br><br>        RuleForEach(x =&gt; x.Items).SetValidator(new OrderItemDtoValidator());<br>    }<br>}<br><br>public class OrderItemDtoValidator : AbstractValidator&lt;OrderItemDto&gt;<br>{<br>    public OrderItemDtoValidator()<br>    {<br>        RuleFor(x =&gt; x.ProductId)<br>            .GreaterThan(0).WithMessage(&quot;Please enter a valid product&quot;);<br><br>        RuleFor(x =&gt; x.Value)<br>            .GreaterThan(0).WithMessage(&quot;Please enter a valid money value!&quot;);<br><br>        RuleFor(x =&gt; x.Currency)<br>            .NotEmpty().WithMessage(&quot;Please enter a money currency code&quot;)<br>            .IsEnumName(typeof(Currency), caseSensitive: false)<br>            .WithMessage(&quot;Please enter a valid currency code!&quot;);<br>    }<br>}</pre><blockquote>“Notice the beauty of the <strong>CreateOrderHandler</strong>: it is very thin. It doesn’t contain <em>if</em> statements about tax rates or validation logic for the address. It simply &#39;tells&#39; the Domain what to do. This makes your application layer incredibly easy to read and maintain, while your Domain layer remains the source of truth for all business rules.&quot;</blockquote><h4>3. The Read Action (Query)</h4><p>Queries are optimized for reading and do not trigger CompleteAsync. Add the codes below into the “GetOrderById” folder.</p><pre>namespace EShoppingTutorial.Core.Application.Orders.Queries.GetOrderById;<br><br>public record GetOrderByIdQuery(int Id) : IRequest&lt;OrderViewModel?&gt;;</pre><pre>namespace EShoppingTutorial.Core.Application.Orders.Queries.GetOrderById;<br><br>internal class GetOrderByIdHandler(IUnitOfWork unitOfWork, IMapper mapper) : IRequestHandler&lt;GetOrderByIdQuery, OrderViewModel?&gt;<br>{<br>    public async Task&lt;OrderViewModel?&gt; Handle(GetOrderByIdQuery request, CancellationToken ct)<br>    {<br>        var order = await unitOfWork.OrderRepository<br>            .GetAsync(predicate: x =&gt; x.Id == new OrderId(request.Id), includes: x =&gt; x.OrderItems)<br>            .ConfigureAwait(false);<br><br>        if (order == null) return null;<br><br>        return mapper.Map&lt;OrderViewModel&gt;(order);<br>    }<br>}</pre><h4>4. The Delete Action (Command)</h4><p>This logic is safely encapsulated in its own file. Add the codes below into the “DeleteOrder” folder.</p><pre>namespace EShoppingTutorial.Core.Application.Orders.Commands.DeleteOrder;<br><br>public record DeleteOrderCommand(OrderId Id) : IRequest&lt;bool&gt;;</pre><pre>namespace EShoppingTutorial.Core.Application.Orders.Commands.DeleteOrder;<br><br>internal class DeleteOrderHandler(IUnitOfWork unitOfWork) : IRequestHandler&lt;DeleteOrderCommand, bool&gt;<br>{<br>    public async Task&lt;bool&gt; Handle(DeleteOrderCommand request, CancellationToken cancellationToken)<br>    {<br>        var order = await unitOfWork.OrderRepository.GetByIdAsync(request.Id).ConfigureAwait(false);<br><br>        if (order is null) return false;<br><br>        unitOfWork.OrderRepository.Remove(order);<br><br>        await unitOfWork.CompleteAsync(cancellationToken).ConfigureAwait(false);<br><br>        return true;<br>    }<br>}</pre><h3>5. Get All Orders Query</h3><p>It is a simple request that returns a list of orders. Add the codes below into the “GetOrderById” folder.</p><pre>namespace EShoppingTutorial.Core.Application.Orders.Queries.GetAllOrders;<br><br>public record GetAllOrdersQuery() : IRequest&lt;QueryResult&lt;OrderViewModel&gt;&gt;;</pre><pre>namespace EShoppingTutorial.Core.Application.Orders.Queries.GetAllOrders;<br><br>internal class GetAllOrdersHandler(IUnitOfWork unitOfWork, IMapper mapper)<br>    : IRequestHandler&lt;GetAllOrdersQuery, QueryResult&lt;OrderViewModel&gt;&gt;<br>{<br>    public async Task&lt;QueryResult&lt;OrderViewModel&gt;&gt; Handle(GetAllOrdersQuery request, CancellationToken ct)<br>    {<br>        var orders = await unitOfWork.OrderRepository<br>            .GetAllAsync(x =&gt; x.OrderItems)<br>            .ConfigureAwait(false);<br><br>        var mappedItems = mapper.Map&lt;IEnumerable&lt;OrderViewModel&gt;&gt;(orders);<br><br>        return new QueryResult&lt;OrderViewModel&gt;(mappedItems, mappedItems.Count());<br>    }<br>}</pre><h3>6. Get Paged Orders Query</h3><p>This is a more advanced query that takes parameters (like Page Index and Page Size) and returns a wrapped result. Add the codes below into the “GetPagedOrders” folder.</p><pre>namespace EShoppingTutorial.Core.Application.Orders.Queries.GetPagedOrders;<br><br>public record GetPagedOrdersQuery(QueryObjectParams QueryObject) : IRequest&lt;QueryResult&lt;OrderViewModel&gt;&gt;;</pre><pre>namespace EShoppingTutorial.Core.Application.Orders.Queries.GetPagedOrders;<br><br>internal class GetPagedOrdersHandler(IUnitOfWork unitOfWork, IMapper mapper)<br>    : IRequestHandler&lt;GetPagedOrdersQuery, QueryResult&lt;OrderViewModel&gt;&gt;<br>{<br>    public async Task&lt;QueryResult&lt;OrderViewModel&gt;&gt; Handle(GetPagedOrdersQuery request, CancellationToken ct)<br>    {<br>        var pagedResult = await unitOfWork.OrderRepository<br>            .GetPageAsync(<br>                request.QueryObject,<br>                predicate: null,<br>                includes: x =&gt; x.OrderItems)<br>            .ConfigureAwait(false);<br><br>        var mappedViewModels = mapper.Map&lt;IEnumerable&lt;OrderViewModel&gt;&gt;(pagedResult.Entities);<br><br>        return new QueryResult&lt;OrderViewModel&gt;(mappedViewModels, pagedResult.TotalCount);<br>    }<br>}</pre><h4>7. Bridging the Gap: Mapping Domain Models to DTOs</h4><p>In Clean Architecture, we must protect our <strong>Domain Entities</strong> from leaking out to the API layer, and similarly, we should avoid using API models to drive our business logic. To manage this translation efficiently, we use <strong>AutoMapper</strong>. Add the codes below into the “Orders” folder.</p><pre>namespace EShoppingTutorial.Core.Application.Orders;<br><br>public static class OrderMappingProfile<br>{<br>    public static void AddMappingConfigs(IMapperConfigurationExpression cfg)<br>    {<br>        // Address -&gt; AddressDto (Simple property matching)<br>        cfg.CreateMap&lt;Address, AddressDto&gt;();<br><br>        // OrderItemDto -&gt; OrderItem<br>        cfg.CreateMap&lt;OrderItemDto, OrderItem&gt;()<br>           .ConstructUsing(src =&gt; new OrderItem(<br>               new ProductId(src.ProductId),<br>               new Price(src.Value, Enum.Parse&lt;Currency&gt;(src.Currency, true))<br>           ));<br><br>        // Scalar Value Object Mappings<br>        cfg.CreateMap&lt;OrderId, int&gt;().ConvertUsing(id =&gt; id.Value);<br>        cfg.CreateMap&lt;ProductId, int&gt;().ConvertUsing(id =&gt; id.Value);<br>        cfg.CreateMap&lt;OrderItemId, int&gt;().ConvertUsing(id =&gt; id.Value);<br><br>        cfg.CreateMap&lt;Price, PriceDto&gt;()<br>            .ForMember(dest =&gt; dest.Value, opt =&gt; opt.MapFrom(src =&gt; src.Value))<br>            .ForMember(dest =&gt; dest.Currency, opt =&gt; opt.MapFrom(src =&gt; src.Currency.ToString()));<br><br>        // Entity -&gt; ViewModel<br>        cfg.CreateMap&lt;Order, OrderViewModel&gt;()<br>            .ForMember(dest =&gt; dest.Id, opt =&gt; opt.MapFrom(src =&gt; src.Id.Value))<br>            // AutoMapper automatically matches ShippingAddress (Address) to ShippingAddress (AddressDto)<br>            .ForMember(dest =&gt; dest.OrderItems, opt =&gt; opt.MapFrom(src =&gt; src.OrderItems));<br><br>        // OrderItem -&gt; OrderItemViewModel<br>        cfg.CreateMap&lt;OrderItem, OrderItemViewModel&gt;()<br>            .ForMember(dest =&gt; dest.Id, opt =&gt; opt.MapFrom(src =&gt; src.Id.Value))<br>            .ForMember(dest =&gt; dest.ProductId, opt =&gt; opt.MapFrom(src =&gt; src.ProductId.Value))<br>            .ForMember(dest =&gt; dest.Price, opt =&gt; opt.MapFrom(src =&gt; src.Price));<br>    }<br>}</pre><blockquote>“By keeping these mappings in the <strong>Application Layer</strong>, we ensure that our Domain remains ‘pure’ and has zero knowledge of the ViewModels used by the outside world. This is a fundamental requirement for maintaining a decoupled and testable system.”</blockquote><h4>Why we use the Command Pattern &amp; MediatR</h4><p>In traditional development, we often create “Fat Services” — single classes like OrderService that grow to thousands of lines. This violates the <strong>Single Responsibility Principle (SRP)</strong> and makes the code a nightmare to maintain. By using the <strong>Command Pattern</strong> via the <strong>MediatR</strong> library, we shift toward <strong>Vertical Slices</strong>:</p><ul><li><strong>Decoupling:</strong> The Web API doesn’t need to know which class handles a request; it just “sends” a command.</li><li><strong>Isolation:</strong> Every use case (e.g., “Delete Order”) lives in its own small class. If you change the delete logic, you cannot accidentally break the “Create Order” logic.</li><li><strong>Scalability:</strong> It’s easy to add cross-cutting concerns like logging, validation, or caching using MediatR Behaviors without touching your business code.</li></ul><h3>Bringing the Web API to Life</h3><p>In this step, we assemble our puzzle. Now that we have built our Domain, Application, and Persistence layers, it is time to host them in a modern <strong>ASP.NET Core 10 Web API</strong>. This is where we wire up our dependencies, connect to the database, and expose our endpoints.</p><p>Before we can wire up our <strong>MediatR</strong> handlers and <strong>Database c</strong>onnection, we need to create the host environment. Here is exactly how to set up the project in Visual Studio.</p><h4>1. Creating the <strong>ASP.NET Core 10 Web API</strong> Project in Visual Studio</h4><ol><li>Click <strong>Create a new project</strong>.</li><li>Search for <strong>ASP.NET Core Web API</strong> and click Next.</li><li><strong>Project Name:</strong> EShoppingTutorialWebAPI.</li><li><strong>Additional Information:</strong></li></ol><ul><li><strong>Framework:</strong> .NET 10.0 (Standard Term Support).</li><li><strong>Enable OpenAPI (Swagger) Support:</strong> Checked (This is vital for testing).</li></ul><h4>2. Essential NuGet Packages</h4><p>Your Web API project acts as the “Entry Point,” so it needs the tools to talk to all other layers and the outside world. Open the <strong>NuGet Package Manager Console</strong> and run these commands:</p><pre># For Database and Migrations<br>dotnet add package Microsoft.EntityFrameworkCore.SqlServer<br>dotnet add package Microsoft.EntityFrameworkCore.Design<br><br># For Orchestration (Application Layer support)<br>dotnet add package MediatR<br><br># For OpenAPI Documentation<br>dotnet add package Swashbuckle.AspNetCore</pre><h4>3. Project References</h4><p>Clean Architecture relies on the direction of dependencies. Your <strong>Web API</strong> project needs to “see” the other projects to register them.</p><ul><li>Right-click <strong>Dependencies</strong> in your Web API project -&gt; <strong>Add Project Reference</strong>.</li><li>Select EShoppingTutorial.Core.Domain</li><li>Select EShoppingTutorial.Core.Application</li><li>Select EShoppingTutorial.Core.Persistence</li><li>Select EShoppingTutorial.Infrastructure</li></ul><h4>4. Creating the GlobalUsings.cs File</h4><p>Create a new file at the root of your Core.Applicationproject. To keep our project clean and maintainable, we utilize <strong>Global Using Directives</strong>.</p><pre>// Frameworks<br>global using MediatR;<br>global using Microsoft.AspNetCore.Identity;<br>global using Microsoft.EntityFrameworkCore;<br>global using FluentValidation;<br><br>// Domain Specific Namespaces<br>global using SharedKernel.Models;<br>global using SharedKernel.Exceptions;<br>global using EShoppingTutorial.Core.Domain;<br>global using EShoppingTutorial.Core.Domain.ValueObjects;<br>global using EShoppingTutorial.Core.Application;<br>global using EShoppingTutorial.Core.Persistence;<br>global using EShoppingTutorial.Core.Domain.Services;<br>global using EShoppingTutorial.Infrastructure.ExternalServices;</pre><h3>The Interface Layer: Implementing the Thin Minimal API</h3><p>The final piece of our architectural puzzle is the <strong>Orders Web API</strong>. In this tutorial, we leverage <strong>.NET 10 Minimal APIs</strong> to implement our entry points. Unlike traditional Controllers, Minimal APIs offer a high-performance, low-ceremony approach to routing. By using <strong>Endpoint Grouping</strong>, we keep our Web API layer incredibly ‘thin,’ acting only as a gateway that directs HTTP traffic into our <strong>Application Layer</strong> via MediatR. This ensures that our architectural boundaries remain strictly respected while benefiting from the latest performance optimizations in the .NET ecosystem. In Clean Architecture, we treat it merely as a delivery mechanism. Its only job is to receive HTTP requests, delegate the work to the Application Layer, and return a response.</p><h4>The MediatR-Powered Order Endpoints</h4><p>By using <strong>MediatR</strong>, our API Endpoint becomes “thin.” It doesn’t contain business logic or even direct references to service implementations. It simply “dispatches” messages. See below how our API Controller has become ‘infrastructure-only’. It doesn’t know about Order entities or even FluentValidation.</p><ol><li><strong>In the add Order method: </strong>The request arrives as a CreateOrderCommand.</li><li><strong>The Guard:</strong> The ValidationBehavior intercepts the command and checks the CreateOrderCommandValidator. If it fails, an exception is thrown before the Handler is ever touched.</li><li><strong>The Transformation:</strong> Inside the CreateOrderCommandHandler, we transform the DTO into a <strong>Rich Domain Entity</strong>.</li></ol><p>This ensures that your Domain Layer stays protected from ‘dirty’ input, and your API Endpoint stays clean of business logic.</p><pre>using EShoppingTutorial.Core.Application.Orders.Commands.CreateOrder;<br>using EShoppingTutorial.Core.Application.Orders.Commands.DeleteOrder;<br>using EShoppingTutorial.Core.Application.Orders.Queries.GetAllOrders;<br>using EShoppingTutorial.Core.Application.Orders.Queries.GetOrderById;<br>using EShoppingTutorial.Core.Application.Orders.Queries.GetPagedOrders;<br><br>public static class OrderEndpoints<br>{<br>    public static void MapOrderEndpoints(this IEndpointRouteBuilder app)<br>    {<br>        var group = app.MapGroup(&quot;/api/order&quot;)<br>                       .WithTags(&quot;Orders&quot;);<br><br>        group.MapGet(&quot;/{id}&quot;, async (int id, IMediator mediator) =&gt;<br>        {<br>            var viewModel = await mediator.Send(new GetOrderByIdQuery(id));<br>            return viewModel is null ? Results.NotFound() : Results.Ok(viewModel);<br>        });<br><br>        group.MapGet(&quot;/GetAll&quot;, async (IMediator mediator) =&gt;<br>            Results.Ok(await mediator.Send(new GetAllOrdersQuery())));<br><br>        group.MapPost(&quot;/GetPaged&quot;, async (QueryObjectParams queryObject, IMediator mediator) =&gt;<br>            Results.Ok(await mediator.Send(new GetPagedOrdersQuery(queryObject))));<br><br>        group.MapPost(&quot;/Add&quot;, async (CreateOrderCommand command, IMediator mediator) =&gt;<br>            Results.Ok(await mediator.Send(command)));<br><br>        group.MapDelete(&quot;/{id}&quot;, async (int id, IMediator mediator) =&gt;<br>        {<br>            var isDeleted = await mediator.Send(new DeleteOrderCommand(new OrderId(id)));<br>            return isDeleted ? Results.Ok() : Results.NotFound();<br>        });<br>    }<br>}</pre><h3>Why This Design is “Clean and Safe”</h3><h4>The Power of MediatR (Decoupling)</h4><p>Instead of injecting five different services for five different features, we only inject IMediator.</p><ul><li><strong>Safety:</strong> The controller doesn’t need to know <em>how</em> an order is deleted or fetched; it only knows <em>who</em> to ask. This prevents the API from becoming a “God Class” as the project grows.</li><li><strong>Clarity:</strong> Each action is a simple call to mediator.Send().</li></ul><blockquote><strong>By the end of this step</strong>, we have achieved the ‘Gold Standard’ of API design. Our OrderAPI is incredibly easy to read because it doesn&#39;t solve problems—it simply routes them. By separating our Request DTOs from our View DTOs, we&#39;ve built a security layer that protects our data integrity. This is the essence of Clean Architecture: every class has one job, every layer is protected, and the system is built to change without breaking.</blockquote><h3>The Safety Net: Centralized Global Exception Handling</h3><p>In a complex DDD application, errors can occur at different levels: a business rule might be violated in the <strong>Domain</strong>, a validation might fail in the <strong>Application</strong> layer, or a database conflict might occur in <strong>Infrastructure</strong>. Instead of cluttering our API Controllers with try-catch blocks, we implement the IExceptionHandler interface introduced in modern .NET.</p><pre>using Microsoft.AspNetCore.Diagnostics;<br><br>public class GlobalExceptionHandler(ILogger&lt;GlobalExceptionHandler&gt; logger) : IExceptionHandler<br>{<br>    public async ValueTask&lt;bool&gt; TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct)<br>    {<br>        logger.LogError(exception, &quot;An error occurred: {Message}&quot;, exception.Message);<br><br>        var (statusCode, title, detail) = exception switch<br>        {<br>            BusinessRuleBrokenException =&gt; (<br>                StatusCodes.Status400BadRequest,<br>                &quot;Business Rule Violation&quot;,<br>                exception.Message),<br><br>            ValidationException valEx =&gt; ( // FluentValidation exception<br>                StatusCodes.Status400BadRequest,<br>                &quot;Validation Error&quot;,<br>                &quot;One or more validation failures occurred.&quot;),<br><br>            DbUpdateConcurrencyException =&gt; (<br>                StatusCodes.Status409Conflict,<br>                &quot;Concurrency Error&quot;,<br>                &quot;The record was modified by another user.&quot;),<br><br>            _ =&gt; (<br>                StatusCodes.Status500InternalServerError,<br>                &quot;Server Error&quot;,<br>                &quot;An unexpected error occurred.&quot;)<br>        };<br><br>        context.Response.StatusCode = statusCode;<br><br>        var response = new<br>        {<br>            status = statusCode,<br>            title = title,<br>            detail = detail,<br>            // If it&#39;s a validation error, add the specific errors<br>            errors = (exception as ValidationException)?.Errors<br>                .GroupBy(x =&gt; x.PropertyName)<br>                .ToDictionary(g =&gt; g.Key, g =&gt; g.Select(x =&gt; x.ErrorMessage).ToArray())<br>        };<br><br>        await context.Response.WriteAsJsonAsync(response, ct);<br>        return true; // Successfully handled<br>    }<br>}</pre><blockquote>“Notice how the API Endpoint Controller remains ‘Thin’. It doesn’t need to know how to format an error message or what HTTP status code a validation failure requires. It simply executes the command, and if something goes wrong, the <strong>GlobalExceptionHandler</strong> ensures the API responds with a consistent, standard JSON contract.”</blockquote><h3>Configuring Program.cs</h3><p>With the packages installed, our Program.cs becomes the &quot;Composition Root.&quot; This is where we register the layers we built throughout the article.</p><pre>namespace EShoppingTutorialWebAPI;<br><br>public class Program<br>{<br>    public static void Main(string[] args)<br>    {<br>        var builder = WebApplication.CreateBuilder(args);<br><br>        // Add Database Connection<br>        builder.Services.AddDbContext&lt;EShoppingTutorialDbContext&gt;(opts =&gt; opts.UseSqlServer(builder.Configuration[&quot;ConnectionStrings:EShoppingTutorialDB&quot;]));<br>        // Add Core Application (Assembly Scanning)<br>        builder.Services.AddCoreApplicationConfigs();<br>        // Presentation Layer Configs <br>        builder.Services.AddControllers();<br>        builder.Services.AddExceptionHandler&lt;GlobalExceptionHandler&gt;();<br>        builder.Services.AddProblemDetails();<br>        // Add Swagger/OpenAPI for testing<br>        builder.Services.AddEndpointsApiExplorer();<br>        builder.Services.AddSwaggerGen();<br>        // Register Application Services and Repositories<br>        builder.Services.AddScoped&lt;IUnitOfWork, UnitOfWork&gt;();<br>        builder.Services.AddTransient&lt;ITaxCalculationService, ExternalTaxProvider&gt;();<br>        // -------- Build the app --------<br>        var app = builder.Build();<br>        if (app.Environment.IsDevelopment())<br>        {<br>            app.UseSwagger();<br>            app.UseSwaggerUI(c =&gt;<br>            {<br>                c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;My API V1&quot;);<br>                c.RoutePrefix = string.Empty;<br>            });<br>        }<br>        app.MapOrderEndpoints();<br>        app.UseExceptionHandler();<br>        app.UseHttpsRedirection();<br>        app.UseAuthorization();<br>        app.MapControllers();<br>        app.UseStaticFiles();<br>        app.UseRouting();<br>        app.Run();<br>    }<br>}</pre><h3>Persisting the Domain: Migrations and Database Creation</h3><p>Now that our Domain, Application, and Infrastructure layers are linked via the Web API, it is time to generate the database schema. Because our DbContext contains complex mappings (Value Converters and Owned Types), Entity Framework Core will translate our Rich Domain Model into a clean, relational structure.</p><ol><li>Before running commands, ensure you have the EF Core global tools installed. Open a terminal and run: “<strong>dotnet tool install — global dotnet-ef”</strong></li><li>The first step in generating a database and tables using a code-first approach is to add database connection strings to appsettings.json in the web API project. Since the Web API is the ‘Startup Project’, EF Core looks there for the connection string during the migration process, even though the database code lives in the Infrastructure layer.</li></ol><blockquote><em>“</em><strong><em>Depending on the database type and configurations:</em></strong><em> your database connection string may differ from the appsettings.json shown below.”</em></blockquote><pre>{<br>  &quot;ConnectionStrings&quot;: {<br>    &quot;EShoppingTutorialDB&quot;: &quot;Data Source=.;Initial Catalog=EShoppingTutorialDB;Integrated Security=True;Pooling=False;TrustServerCertificate=True&quot;<br>  }<br>}</pre><p>3. Open your Terminal or Package Manager Console and run these commands to sync your database:</p><ul><li><strong>Adding the Initial Migration: </strong>We need to point the tool to the project containing the DbContext (EShoppingTutorial.Core.Persistence) and the startup project (EShoppingTutorialWebAPI), run: dotnet ef migrations add InitialCreate --project EShoppingTutorial.Core.Persistence --startup-project EShoppingTutorialWebAPI</li><li><strong>What happens here?</strong> EF Core scans your OrderConfiguration and OrderItemConfiguration. It notices the OwnsOne mapping for Price and creates Price_Value and Price_Currency columns inside the OrderItems table.</li><li><strong>Updating the Database: </strong>To push the migration to your SQL Server (or your configured provider) and create the physical database, run: dotnet ef database update --startup-project EShoppingTutorialWebAPI</li></ul><p>Once the command completes, you can open <strong>SQL Server Management Studio (SSMS)</strong> or the <strong>VS Code Database Client</strong> to see the “Tactical DDD” result in table form:</p><ul><li><strong>Tables:</strong> You will see Orders and OrderItems.</li><li><strong>Strongly Typed IDs:</strong> Notice that even though we used OrderId and OrderItemId in C#, the columns are standard INT types thanks to our Value Converters.</li><li><strong>Flattened Value Objects:</strong> The OrderItems table contains the price data without needing a separate &quot;Prices&quot; table, maintaining high performance.</li></ul><h3>Common Troubleshooting Tip</h3><blockquote>“If you receive a ‘Connection String’ error, double-check your appsettings.json in the <strong>Web API project</strong>. Since the Web API is the &#39;Startup Project&#39;, EF Core looks there for the connection string during the migration process, even though the database code lives in the Infrastructure layer.”</blockquote><h3>Testing the Implementation: Creating Your First Order</h3><p>With the database schema ready and the global exception handler in place, we can now verify the entire flow: from the <strong>API Controller</strong>, through the <strong>MediatR Handler</strong>, into the <strong>Domain Logic</strong>, and finally persisting via the <strong>Unit of Work</strong>. We use <strong>Swagger</strong> as our primary testing tool, allowing us to send POST and GET requests to our MediatR handlers immediately.</p><h4>1. Launching the API</h4><p>Press F5 or run dotnet run from your Web API project folder. By default, your browser should open to the <strong>Swagger UI</strong> (typically at <a href="https://localhost:xxxx/swagger).">https://localhost:xxxx/swagger).</a></p><h4>2. Sending a “Create Order” Request</h4><p>Locate the POST /api/Order endpoint. We will send a JSON payload that includes our CreateOrderCommandDto structure. This will test our <strong>AutoMapper</strong> configuration and our <strong>Domain Constructor</strong> logic.</p><p>Example Request Body:</p><pre>{<br>  &quot;customerId&quot;: 1,<br>  &quot;street&quot;: &quot;Adam-Klein&quot;,<br>  &quot;city&quot;: &quot;New York&quot;,<br>  &quot;country&quot;: &quot;USA&quot;,<br>  &quot;zipCode&quot;: &quot;07008&quot;,<br>  &quot;items&quot;: [<br>    {<br>      &quot;productId&quot;: 2,<br>      &quot;value&quot;: 15.50,<br>      &quot;currency&quot;: &quot;USD&quot;<br>    }<br>  ]<br>}</pre><h4>3. What to Observe</h4><ul><li><strong>Validation:</strong> If you try to send a negative Price Value, your FluentValidation (and the GlobalExceptionHandler) should return a structured 400 Bad Request.</li><li><strong>Database Persistence:</strong> After a successful 200 OK response, check your SQL OrderItems table. You will see that the Price Value Object was correctly flattened into Value and Currency columns.</li><li><strong>The Response:</strong> The response you get back is a mapped OrderViewModel. Notice that the OrderId record was converted into a clean integer for the client.</li></ul><h4>4. Verifying “GetAll” and “GetPaged”</h4><p>Now, use the GET /api/Order/GetAll or the POST /api/Order/GetPaged endpoints. These will test the reverse flow: fetching entities with their Includes, mapping them to ViewModels, and wrapping them in our QueryResult DTO.</p><h3>Conclusion: A Future-Proof Foundation</h3><p>We have successfully journeyed through the layers of Clean Architecture, transforming a simple e-commerce concept into a robust, enterprise-ready Web API. By following these principles, you haven’t just built an application; you’ve built a <strong>system</strong> designed to last. You’ve built a system where:</p><ol><li><strong>The Domain is King:</strong> Business rules are protected inside Entities.</li><li><strong>The Architecture is Clean:</strong> Layers are decoupled, making the system easy to test and maintain.</li><li><strong>The API is Professional:</strong> Errors are handled globally, and data is exposed through safe, flattened DTOs.</li></ol><h3>Final Summary of our Architecture</h3><ul><li><strong>Domain Layer:</strong> The heart of our system, containing pure business logic and entities, completely isolated from external frameworks.</li><li><strong>Application Layer:</strong> The brain, using <strong>MediatR</strong> and the <strong>Command Pattern</strong> to orchestrate use cases without bloating our services.</li><li><strong>Persistence Layer:</strong> The shield, managing database complexities and ensuring data integrity through the <strong>Unit of Work</strong> and <strong>Repository</strong> patterns.</li><li><strong>Web Minimal API Layer:</strong> The interface, kept “thin” and “clean” by delegating responsibility to MediatR and using <strong>AOP (</strong>Aspect-Oriented Programming<strong>) Filters</strong> for global error handling.</li></ul><h3>Why This Matters</h3><p>In the fast-paced world of software development, requirements change. Databases get swapped, UI frameworks evolve, and business rules shift. By decoupling your code today, you’ve ensured that:</p><ol><li><strong>Testing is easy:</strong> You can test business logic without a database.</li><li><strong>Maintenance is simple:</strong> Bug fixes in one slice won’t break another.</li><li><strong>Onboarding is fast:</strong> New developers can look at a single folder to understand a whole feature.</li></ol><h3>Next Steps</h3><p>You have successfully implemented the <strong>Order Management Context</strong> using a Tactical DDD approach. While we have a solid foundation, the journey of Domain-Driven Design doesn’t end here. To take this project to a production-ready level, consider exploring these advanced topics:</p><h4>1. Domain Events</h4><p>Currently, when an order is created, the system just saves it. In a real system, you might need to notify the <strong>Inventory</strong> to reserve stock or the <strong>Shipping</strong> context to prepare a label. Implementing <strong>Domain Events</strong> (and a Dispatcher) allows you to trigger these side effects without tightly coupling your Order logic to other services.</p><h4>2. Outbox Pattern</h4><p>To ensure reliability in a distributed system, you can implement the <strong>Outbox Pattern</strong>. This ensures that your database update and your message broadcasting (to RabbitMQ or Azure Service Bus) happen within a single transaction, preventing data inconsistency.</p><h4>3. Moving to Microservices</h4><p>Now that your Order Management is encapsulated in its own <strong>Bounded Context</strong>, it is a prime candidate to be moved into its own microservice. Because we used a Clean Architecture, the transition would mostly involve moving the code and changing the infrastructure layer to use its own database.</p><h3>Final Thought</h3><blockquote>“Software development is not just about writing code; it’s about managing complexity. DDD provides the tools to master this complexity by focusing on the core of the business. The difference between a coder and an architect is the ability to see the ‘big picture.’ Clean Architecture allows you to stop fighting the framework and start focusing on the business value.”</blockquote><p><strong>Thank you for following along with this Article! If you found this helpful, feel free to share it with your fellow developers. Happy coding!</strong></p><h3>Source Code</h3><p>For those who want to dive straight into the implementation, the complete source code is available on my GitHub: <strong>→ </strong><a href="https://github.com/tomajexpress/Domain.Driven.Implementation.In.CSharp.NET.Core.git"><strong>Download Source Code from GitHub</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5255d71d609f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>