<?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 Chandrashekhar Singh on Medium]]></title>
        <description><![CDATA[Stories by Chandrashekhar Singh on Medium]]></description>
        <link>https://medium.com/@chandrashekharsingh25?source=rss-796c5dd99155------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZKMuDGTBpDQMHnqBVQkxtA.jpeg</url>
            <title>Stories by Chandrashekhar Singh on Medium</title>
            <link>https://medium.com/@chandrashekharsingh25?source=rss-796c5dd99155------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 16:55:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chandrashekharsingh25/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[Stop Creating Fake Data Manually — Use Bogus in .NET 10]]></title>
            <link>https://medium.com/@chandrashekharsingh25/stop-creating-fake-data-manually-use-bogus-in-net-10-3dc160e283d9?source=rss-796c5dd99155------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dc160e283d9</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-10]]></category>
            <category><![CDATA[dot-net-framework]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Chandrashekhar Singh]]></dc:creator>
            <pubDate>Fri, 08 May 2026 05:15:19 GMT</pubDate>
            <atom:updated>2026-05-08T05:20:41.580Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NitE97w_3AXCUsPsoLM5kg.png" /></figure><blockquote>Every developer has been there — staring at a blank test file, typing &quot;John Doe&quot; for the hundredth time. There&#39;s a better way.</blockquote><h3>The Dirty Secret of Most .NET Test Suites</h3><p>Open up any .NET project&#39;s test folder and you&#39;ll almost certainly find something like this:</p><pre>var customer = new Customer<br>{<br>    Name = &quot;Test User&quot;,<br>    Email = &quot;test@test.com&quot;,<br>    Phone = &quot;1234567890&quot;<br>};</pre><p>It works. Technically. But it&#39;s fragile, it&#39;s boring, and honestly — it gives you false confidence. Your tests only ever run against that one exact input. What happens when a real user&#39;s name has an apostrophe? What if their email has a plus sign? What if the city field is longer than expected?</p><p>That&#39;s the gap the <strong>Bogus</strong> package was built to fill.</p><h3>What Exactly is Bogus?</h3><p>Bogus is an open-source .NET library created by <strong>Brian Chavez</strong>, inspired by the JavaScript library <strong>Faker.js</strong>. It generates realistic, randomized fake data using a clean fluent API — names, emails, addresses, phone numbers, prices, dates, GUIDs, product names, you name it.</p><p>One line of setup. Infinite variety.</p><pre>dotnet add package Bogus</pre><p>That&#39;s your entire installation. No configuration files, no registration, no ceremony. Just install and go.</p><p>It works with every modern .NET version, and it slots perfectly into .NET 10 Web API projects whether you&#39;re seeding a database, writing unit tests, or spinning up a mock endpoint for a client demo.</p><h3>Setting It Up in a .NET 10 Web API</h3><pre>dotnet new webapi -n BogusDemo --framework net10.0<br>cd BogusDemo<br>dotnet add package Bogus</pre><p>Now define a model — let&#39;s use something real-world:</p><pre>public class Customer<br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>    public string Email { get; set; }<br>    public string Phone { get; set; }<br>    public string City { get; set; }<br>    public DateTime DateOfBirth { get; set; }<br>}</pre><p>And here&#39;s where Bogus earns its keep:</p><pre>using Bogus;<br><br>var faker = new Faker&lt;Customer&gt;()<br>    .RuleFor(c =&gt; c.Id, f =&gt; f.IndexFaker + 1)<br>    .RuleFor(c =&gt; c.Name, f =&gt; f.Name.FullName())<br>    .RuleFor(c =&gt; c.Email, f =&gt; f.Internet.Email())<br>    .RuleFor(c =&gt; c.Phone, f =&gt; f.Phone.PhoneNumber())<br>    .RuleFor(c =&gt; c.City, f =&gt; f.Address.City())<br>    .RuleFor(c =&gt; c.DateOfBirth, f =&gt; f.Date.Past(30));<br><br>var customers = faker.Generate(5);</pre><p>Run that and here&#39;s what comes out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VsOiUdtIo7tnnWCgNKrqpg.png" /></figure><p>Not &quot;Test User 1&quot;. Not &quot;foo@bar.com&quot;. Actual human-looking data that you&#39;d see in a real application.</p><h3>Using Bogus Directly Inside a .NET 10 API Endpoint</h3><p>This is a pattern that&#39;s genuinely useful early in a project — before your database is wired up, you can still return real-looking responses:</p><pre>// Program.cs<br>app.MapGet(&quot;/api/customers&quot;, () =&gt;<br>{<br>    var faker = new Faker&lt;Customer&gt;()<br>        .RuleFor(c =&gt; c.Id, f =&gt; f.IndexFaker + 1)<br>        .RuleFor(c =&gt; c.Name, f =&gt; f.Name.FullName())<br>        .RuleFor(c =&gt; c.Email, f =&gt; f.Internet.Email())<br>        .RuleFor(c =&gt; c.Phone, f =&gt; f.Phone.PhoneNumber())<br>        .RuleFor(c =&gt; c.City, f =&gt; f.Address.City())<br>        .RuleFor(c =&gt; c.DateOfBirth, f =&gt; f.Date.Past(30));<br><br>    return Results.Ok(faker.Generate(10));<br>});</pre><p>Hit /api/customers and you get 10 well-formed customer objects instantly — no database, no migration, no seed scripts. Your frontend developer can start building against real-looking data the same day you create the project.</p><h3>Why Bogus is a Game-Changer for Unit Testing</h3><p>This is where the real value lives. Let&#39;s be honest about what bad test data actually costs you.</p><h3>The Problem with Hardcoded Test Data</h3><pre>// This test looks fine. It isn&#39;t.<br>var customer = new Customer { Name = &quot;John&quot;, Email = &quot;john@test.com&quot; };<br>var result = _service.Create(customer);<br>Assert.True(result.IsSuccess);</pre><p>That test passes — but only for that exact combination of inputs. It tells you almost nothing about how your service handles the thousand other combinations a real user might throw at it.</p><h3>The Bogus Approach</h3><pre>var customer = new Faker&lt;Customer&gt;()<br>    .RuleFor(c =&gt; c.Name, f =&gt; f.Name.FullName())<br>    .RuleFor(c =&gt; c.Email, f =&gt; f.Internet.Email())<br>    .Generate();<br><br>var result = _service.Create(customer);<br>Assert.True(result.IsSuccess);</pre><p>Every run uses different data. Different names, different email formats, different lengths. Your test suite starts discovering edge cases that would have slipped straight to production otherwise.</p><h3>A Complete xUnit Test Class with Bogus</h3><pre>public class CustomerServiceTests<br>{<br>    private readonly Faker&lt;Customer&gt; _faker;<br>    private readonly CustomerService _service;<br><br>    public CustomerServiceTests()<br>    {<br>        _faker = new Faker&lt;Customer&gt;()<br>            .RuleFor(c =&gt; c.Id, f =&gt; f.Random.Int(1, 1000))<br>            .RuleFor(c =&gt; c.Name, f =&gt; f.Name.FullName())<br>            .RuleFor(c =&gt; c.Email, f =&gt; f.Internet.Email())<br>            .RuleFor(c =&gt; c.Phone, f =&gt; f.Phone.PhoneNumber());<br><br>        _service = new CustomerService();<br>    }<br><br>    [Fact]<br>    public void CreateCustomer_WithValidData_ShouldSucceed()<br>    {<br>        var customer = _faker.Generate();<br>        var result = _service.Create(customer);<br>        Assert.True(result.IsSuccess);<br>    }<br><br>    [Fact]<br>    public void CreateMultipleCustomers_ShouldAllHaveUniqueIds()<br>    {<br>        var customers = _faker.Generate(50);<br>        var uniqueIds = customers.Select(c =&gt; c.Id).Distinct().Count();<br>        Assert.Equal(50, uniqueIds);<br>    }<br>}</pre><p>Clean. Readable. Tests that actually mean something.</p><h3>Reproducible Tests with a Fixed Seed</h3><p>Sometimes you want randomness — but not in CI/CD, where flaky tests are the enemy. Bogus has a seed feature that locks the output:</p><pre>var faker = new Faker&lt;Customer&gt;()<br>    .UseSeed(42)<br>    .RuleFor(c =&gt; c.Name, f =&gt; f.Name.FullName())<br>    .RuleFor(c =&gt; c.Email, f =&gt; f.Internet.Email());<br><br>// Seed 42 will always generate the exact same customer<br>var customer = faker.Generate();</pre><p>Use random seeds locally to catch edge cases. Use a fixed seed in your pipeline to keep builds deterministic. Best of both worlds.</p><h3>The Benefits That Actually Matter</h3><h3>Realistic Data, Not Placeholder Noise</h3><p>&quot;Test User&quot;, &quot;foo@bar.com&quot;, &quot;123 Fake St&quot; — this data is noise. It adds nothing to your confidence in the system. Bogus generates data that looks like it came from real users, which means your tests, your demos, and your seed data are all significantly more meaningful.</p><h3>A Fluent API That Reads Like English</h3><p>The RuleFor syntax is clean enough that a non-developer could probably guess what it does:</p><pre>.RuleFor(c =&gt; c.City, f =&gt; f.Address.City())</pre><p>No documentation needed. No mental overhead. You write it once and move on.</p><h3>30+ Locales for International Projects</h3><p>Building something for a global audience? Bogus generates culturally appropriate data for over 30 locales:</p><pre>var faker = new Faker(&quot;de&quot;); // German locale<br>var name = faker.Name.FullName(); // Generates German-style names<br><br>var japaneseFaker = new Faker(&quot;ja&quot;); // Japanese locale</pre><h3>Every Data Type You Will Ever Need</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJzvyY7_MUFwkMrLhWp9vg.png" /></figure><h3>Database Seeding in Minutes, Not Hours</h3><p>This is one of the most practical use cases. Instead of writing SQL insert scripts or manually populating a database, just run this at startup:</p><pre>// DbSeeder.cs<br>public static class DbSeeder<br>{<br>    public static void Seed(AppDbContext context)<br>    {<br>        if (context.Products.Any()) return;<br><br>        var productFaker = new Faker&lt;Product&gt;()<br>            .RuleFor(p =&gt; p.Name, f =&gt; f.Commerce.ProductName())<br>            .RuleFor(p =&gt; p.Price, f =&gt; f.Finance.Amount(10, 500))<br>            .RuleFor(p =&gt; p.Category, f =&gt; f.Commerce.Department())<br>            .RuleFor(p =&gt; p.Stock, f =&gt; f.Random.Int(0, 200))<br>            .RuleFor(p =&gt; p.CreatedAt, f =&gt; f.Date.Past(1));<br><br>        context.Products.AddRange(productFaker.Generate(500));<br>        context.SaveChanges();<br>    }<br>}</pre><p>500 realistic products. Done. Your local environment looks like a real store from day one.</p><h3>Zero Risk to Production</h3><p>Bogus is purely a development and testing tool. It generates data in memory — no network access, no external dependencies, and no way to affect production. You reference it only in test projects or behind an environment check, so there is no accidental leakage.</p><h3>When You Should Use Bogus — and When You Shouldn&#39;t</h3><h3>Use It When...</h3><p><strong>Writing unit and integration tests</strong> — Any time you need object instances to pass to a service, controller, or repository, Bogus beats hardcoded data every time. Your tests become more robust without any extra effort.</p><p><strong>Seeding a development or staging database</strong> — New team member joining? Fresh environment being spun up? Bogus gives everyone a fully populated database that actually looks like production data.</p><p><strong>Showing your API to a client or stakeholder</strong> — &quot;Test User 1&quot; and &quot;test@test.com&quot; undermine the professional impression you&#39;re trying to make. Realistic fake data makes your demo feel polished and production-ready.</p><p><strong>Load and performance testing</strong> — Tools like k6 and JMeter need large volumes of varied data. Generating 100,000 unique user records manually is not realistic. Bogus does it in seconds.</p><p><strong>Building mock API endpoints</strong> — When your frontend team needs to move faster than your backend, Bogus-powered endpoints let them build against real-looking responses without waiting on a database.</p><h3>Skip It When...</h3><p><strong>Your test depends on a specific, exact value</strong> — If you&#39;re testing that an email must contain &quot;@&quot;, hardcode the input. Bogus randomness would work against you here.</p><p><strong>You&#39;re working with strict domain validation rules</strong> — If your business logic demands very specific data formats that Bogus doesn&#39;t know about (custom ID formats, proprietary codes), you&#39;ll spend more time configuring Bogus than it saves you. A dedicated Test Data Builder pattern might be a cleaner fit.</p><p><strong>It&#39;s anything touching production</strong> — Bogus has no place in production code. Keep it in test projects and development startup code only.</p><h3>Three Pro Tips Worth Knowing</h3><h3>Tip 1 — Build a Centralized Faker Factory</h3><p>Don&#39;t define your fakers inline in every test. Create a shared factory once and reuse it everywhere:</p><pre>// FakerFactory.cs<br>public static class FakerFactory<br>{<br>    public static Faker&lt;Customer&gt; Customer() =&gt;<br>        new Faker&lt;Customer&gt;()<br>            .RuleFor(c =&gt; c.Id, f =&gt; f.IndexFaker + 1)<br>            .RuleFor(c =&gt; c.Name, f =&gt; f.Name.FullName())<br>            .RuleFor(c =&gt; c.Email, f =&gt; f.Internet.Email());<br><br>    public static Faker&lt;Product&gt; Product() =&gt;<br>        new Faker&lt;Product&gt;()<br>            .RuleFor(p =&gt; p.Name, f =&gt; f.Commerce.ProductName())<br>            .RuleFor(p =&gt; p.Price, f =&gt; f.Finance.Amount(5, 999));<br>}</pre><p>Every test class just calls FakerFactory.Customer().Generate(). One place to update when your model changes.</p><h3>Tip 2 — Test Your AutoMapper Profiles with Bogus DTOs</h3><pre>var fakeDto = new Faker&lt;CreateCustomerDto&gt;()<br>    .RuleFor(d =&gt; d.Name, f =&gt; f.Name.FullName())<br>    .RuleFor(d =&gt; d.Email, f =&gt; f.Internet.Email())<br>    .Generate();<br><br>var customer = _mapper.Map&lt;Customer&gt;(fakeDto);<br><br>Assert.Equal(fakeDto.Name, customer.Name);<br>Assert.Equal(fakeDto.Email, customer.Email);</pre><p>Mapping bugs caught early. No hardcoded DTOs. Clean test.</p><h3>Tip 3 — Use PickRandom&lt;TEnum&gt;() for Status Fields</h3><pre>public enum OrderStatus { Pending, Processing, Shipped, Delivered, Cancelled }<br><br>var faker = new Faker&lt;Order&gt;()<br>    .RuleFor(o =&gt; o.Status, f =&gt; f.PickRandom&lt;OrderStatus&gt;())<br>    .RuleFor(o =&gt; o.Total, f =&gt; f.Finance.Amount(20, 500));</pre><p>Your tests now run against every possible order status automatically, not just the one you thought to hardcode.</p><h3>Quick Reference Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-KwK6GaSV8XhO31T7iQGg.png" /></figure><h3>The Bottom Line</h3><p>Most developers reach for Bogus once — maybe to populate a demo database — and then quietly start using it everywhere. Unit tests, integration tests, seed scripts, mock endpoints. It earns its place because it solves a real, daily pain point without asking anything complicated of you.</p><p>The fluent API takes about five minutes to learn. The time you save compared to writing and maintaining hardcoded test data adds up to hours per project. And the confidence boost from running your tests against genuinely varied data? That&#39;s harder to put a number on, but it&#39;s real.</p><p>If you&#39;re building a .NET 10 Web API and you haven&#39;t added Bogus to your test toolkit yet, that&#39;s the one change worth making this week.</p><pre>dotnet add package Bogus</pre><p>Start with one test class. You&#39;ll have it in five others by Friday.</p><p><em>Happy Coding! 🚀</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dc160e283d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Async/Await Rules That Can Instantly Improve Your C# Code in .NET 10 Web API]]></title>
            <link>https://medium.com/@chandrashekharsingh25/10-async-await-rules-that-can-instantly-improve-your-c-code-in-net-10-web-api-0b80fd242a10?source=rss-796c5dd99155------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b80fd242a10</guid>
            <category><![CDATA[csharp-programming]]></category>
            <category><![CDATA[await]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Chandrashekhar Singh]]></dc:creator>
            <pubDate>Sun, 03 May 2026 05:22:23 GMT</pubDate>
            <atom:updated>2026-05-03T05:22:23.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJOr_nthMOp3usN2nKmz2w.png" /></figure><h3>🧠 First, Let’s Truly Understand Async/Await</h3><p>Before jumping into rules, let’s get a rock-solid mental model of what async/await actually does under the hood.</p><h3>What Problem Does It Solve?</h3><p>In a traditional <strong>synchronous</strong> Web API, every incoming HTTP request occupies a thread for its entire duration. If your handler calls a database and waits 200ms for the result, that thread sits idle — blocked — doing nothing. Under load, you run out of threads, and new requests queue up. The server chokes.</p><p><strong>Async/await solves this by freeing threads while waiting.</strong></p><h3>How It Works (Simply)</h3><p>When you await an operation:</p><ol><li>The current thread is <strong>released back to the thread pool</strong></li><li>The runtime registers a <strong>continuation</strong> — “when the result is ready, resume here”</li><li>When the I/O completes, a thread (possibly different) <strong>picks up where you left off</strong></li></ol><p>Your code <em>looks</em> sequential but is <strong>non-blocking</strong> underneath.</p><pre>// Synchronous - thread is BLOCKED for 200ms<br>public IActionResult GetUser(int id)<br>{<br>    var user = _db.Users.Find(id); // thread waits here<br>    return Ok(user);<br>}<br><br>// Asynchronous - thread is FREED during the DB call<br>public async Task&lt;IActionResult&gt; GetUserAsync(int id)<br>{<br>    var user = await _db.Users.FindAsync(id); // thread released, reclaimed later<br>    return Ok(user);<br>}</pre><h3>The Task Model</h3><ul><li>Task → represents an async operation that returns <strong>void</strong></li><li>Task&lt;T&gt; → represents an async operation that returns <strong>a value of type T</strong></li><li>ValueTask&lt;T&gt; → a lightweight alternative for hot paths (more on this later)</li></ul><h3>The State Machine</h3><p>When the compiler sees async, it transforms your method into a <strong>state machine</strong>. Each await becomes a state transition point. This is why you can&#39;t use await in a regular method — the compiler needs to rewrite it entirely.</p><pre>Method called<br>     ↓<br>State 0: Execute until first await<br>     ↓<br>Await hit → release thread → register continuation<br>     ↓<br>I/O completes → thread resumes<br>     ↓<br>State 1: Execute until next await (or return)</pre><p>Now that the foundation is solid — let’s talk rules.</p><h3>Rule 1: Always Await Async Methods — Never Fire and Forget</h3><h3>❌ Wrong</h3><pre>[HttpPost(&quot;send-email&quot;)]<br>public IActionResult SendWelcomeEmail(string email)<br>{<br>    _emailService.SendAsync(email); // Task is NOT awaited — dangerous!<br>    return Ok(&quot;Done&quot;);<br>}</pre><h3>✅ Correct</h3><pre>[HttpPost(&quot;send-email&quot;)]<br>public async Task&lt;IActionResult&gt; SendWelcomeEmail(string email)<br>{<br>    await _emailService.SendAsync(email);<br>    return Ok(&quot;Done&quot;);<br>}</pre><p><strong>What goes wrong without await?</strong></p><ul><li>Exceptions are silently swallowed</li><li>The operation may not complete before the response is sent</li><li>In .NET, unobserved task exceptions can crash the process</li></ul><p><strong>When you genuinely want fire-and-forget</strong>, use a background service (IHostedService, BackgroundService, or IBackgroundTaskQueue) — not an unawaited task.</p><p><strong>✅ Benefit:</strong> Guaranteed exception propagation and operation completion.</p><p><strong>📌 When to use:</strong> Always, unless explicitly offloading to a proper background worker.</p><p><strong>🚫 When not to use:</strong> Do not fire-and-forget for critical operations like payment processing, email delivery, or audit logging.</p><h3>Rule 2: Use ConfigureAwait(false) in Library/Service Code</h3><h3>❌ Wrong (in a service layer)</h3><pre>public async Task&lt;Order&gt; GetOrderAsync(int id)<br>{<br>    var order = await _repository.GetAsync(id); // captures SynchronizationContext<br>    return order;<br>}</pre><h3>✅ Correct</h3><pre>public async Task&lt;Order&gt; GetOrderAsync(int id)<br>{<br>    var order = await _repository.GetAsync(id).ConfigureAwait(false);<br>    return order;<br>}</pre><p><strong>Why does this matter?</strong></p><p>In ASP.NET Core, there is no SynchronizationContext (unlike WinForms/WPF), so this is less critical — but in <strong>library code</strong> that might be consumed in multiple environments, ConfigureAwait(false) avoids unnecessary context switching and prevents potential deadlocks.</p><p><strong>✅ Benefit:</strong> Prevents deadlocks in non-ASP.NET environments; slightly better performance.</p><p><strong>📌 When to use:</strong> Repository classes, service layers, NuGet packages, any reusable code.</p><p><strong>🚫 When not to use:</strong> Controller actions or middleware where you need the HTTP context after the await.</p><h3>Rule 3: Use async Task Not async void</h3><h3>❌ Wrong</h3><pre>public async void ProcessOrderAsync(Order order) // void is dangerous!<br>{<br>    await _service.ProcessAsync(order);<br>}</pre><h3>✅ Correct</h3><pre>public async Task ProcessOrderAsync(Order order)<br>{<br>    await _service.ProcessAsync(order);<br>}</pre><p><strong>Why is </strong><strong>async void dangerous?</strong></p><ul><li>Exceptions thrown inside async void <strong>cannot be caught</strong> by the caller</li><li>The caller has no way to await it or know when it completes</li><li>It crashes the application with an unhandled exception</li></ul><p><strong>The only valid use of </strong><strong>async void</strong> is event handlers (e.g., button click in WinForms) where the signature is forced.</p><pre>// ONLY acceptable async void usage<br>private async void OnButtonClick(object sender, EventArgs e)<br>{<br>    await DoSomethingAsync();<br>}</pre><p><strong>✅ Benefit:</strong> Full exception handling and awaitable completion.</p><p><strong>📌 When to use:</strong> Everywhere. Make every async method return Task or Task&lt;T&gt;.</p><p><strong>🚫 When not to use:</strong> Never use async void in Web API controllers, services, or repositories.</p><h3>Rule 4: Run Independent Tasks in Parallel with Task.WhenAll</h3><h3>❌ Wrong (Sequential — unnecessarily slow)</h3><pre>[HttpGet(&quot;dashboard/{userId}&quot;)]<br>public async Task&lt;IActionResult&gt; GetDashboard(int userId)<br>{<br>    var orders = await _orderService.GetOrdersAsync(userId);    // 100ms<br>    var profile = await _profileService.GetProfileAsync(userId); // 80ms<br>    var notifications = await _notifService.GetAsync(userId);   // 60ms<br>    // Total: ~240ms<br>    return Ok(new { orders, profile, notifications });<br>}</pre><h3>✅ Correct (Parallel — all run at the same time)</h3><pre>[HttpGet(&quot;dashboard/{userId}&quot;)]<br>public async Task&lt;IActionResult&gt; GetDashboard(int userId)<br>{<br>    var ordersTask       = _orderService.GetOrdersAsync(userId);<br>    var profileTask      = _profileService.GetProfileAsync(userId);<br>    var notificationsTask = _notifService.GetAsync(userId);<br><br>    await Task.WhenAll(ordersTask, profileTask, notificationsTask);<br>    // Total: ~100ms (the slowest one)<br>    return Ok(new<br>    {<br>        orders        = ordersTask.Result,<br>        profile       = profileTask.Result,<br>        notifications = notificationsTask.Result<br>    });<br>}</pre><p><strong>✅ Benefit:</strong> Dramatic latency reduction when operations are independent.</p><p><strong>📌 When to use:</strong> Multiple independent I/O calls in a single request — database reads, HTTP calls, cache lookups.</p><p><strong>🚫 When not to use:</strong> When operations depend on each other’s results, or when you need to limit parallelism to avoid overwhelming a downstream service.</p><h3>Rule 5: Prefer ValueTask&lt;T&gt; for Hot Paths with Cached Results</h3><h3>❌ Suboptimal for frequent cache hits</h3><pre>public async Task&lt;Product&gt; GetProductAsync(int id)<br>{<br>    if (_cache.TryGet(id, out var cached))<br>        return cached; // allocates a Task&lt;Product&gt; unnecessarily<br><br>        return await _db.Products.FindAsync(id);<br>}</pre><h3>✅ Correct</h3><pre>public async ValueTask&lt;Product&gt; GetProductAsync(int id)<br>{<br>    if (_cache.TryGet(id, out var cached))<br>        return cached; // no Task allocation — stack-based ValueTask<br><br>       return await _db.Products.FindAsync(id);<br>}</pre><p><strong>Why does this matter?</strong></p><p>Task&lt;T&gt; is a reference type — every synchronous return allocates an object on the heap. In high-throughput APIs serving thousands of requests per second, this adds up to significant GC pressure. ValueTask&lt;T&gt; avoids the allocation when the result is already available.</p><p><strong>✅ Benefit:</strong> Reduced heap allocations, less GC pressure, better throughput on hot paths.</p><p><strong>📌 When to use:</strong> Methods that frequently return synchronously (e.g., cache hits), performance-critical code.</p><p><strong>🚫 When not to use:</strong> General application code — the complexity isn’t worth it if the path is rarely synchronous.</p><h3>Rule 6: Use CancellationToken Everywhere</h3><h3>❌ Wrong</h3><pre>[HttpGet(&quot;products&quot;)]<br>public async Task&lt;IActionResult&gt; GetProducts()<br>{<br>    var products = await _db.Products.ToListAsync(); // ignores client disconnect<br>    return Ok(products);<br>}</pre><h3>✅ Correct</h3><pre>[HttpGet(&quot;products&quot;)]<br>public async Task&lt;IActionResult&gt; GetProducts(CancellationToken cancellationToken)<br>{<br>    var products = await _db.Products<br>        .ToListAsync(cancellationToken); // cancelled when client disconnects<br>    return Ok(products);<br>}</pre><p>ASP.NET Core automatically binds CancellationToken from the HTTP request lifecycle. When the client disconnects or the request times out, the token is cancelled — and so is your database query, HTTP call, or any other awaitable.</p><p><strong>Propagate it everywhere:</strong></p><pre>public async Task&lt;List&lt;Product&gt;&gt; GetProductsAsync(CancellationToken ct)<br>{<br>    var raw = await _db.Products.ToListAsync(ct);<br>    var enriched = await _enrichmentService.EnrichAsync(raw, ct);<br>    return enriched;<br>}</pre><p><strong>✅ Benefit:</strong> Frees resources when clients disconnect; prevents wasted work; enables request timeouts.</p><p><strong>📌 When to use:</strong> Every async controller action, service method, and repository call.</p><p><strong>🚫 When not to use:</strong> Operations that <strong>must</strong> complete regardless of client state (e.g., financial transaction commits, audit log writes).</p><h3>Rule 7: Never Use .Result or .Wait() on a Task</h3><h3>❌ Wrong — Classic Deadlock Recipe</h3><pre>public IActionResult GetUser(int id)<br>{<br>    // .Result BLOCKS the thread and can cause deadlocks<br>    var user = _userService.GetUserAsync(id).Result;<br>    return Ok(user);<br>}</pre><h3>✅ Correct</h3><pre>public async Task&lt;IActionResult&gt; GetUser(int id)<br>{<br>    var user = await _userService.GetUserAsync(id);<br>    return Ok(user);<br>}</pre><p><strong>Why does </strong><strong>.Result deadlock?</strong></p><p>In environments with a SynchronizationContext (WPF, WinForms, old ASP.NET), .Result blocks the current thread. The async continuation needs that same thread to complete. Deadlock — neither side can proceed.</p><p>Even in ASP.NET Core (no SynchronizationContext), .Result still blocks a thread pool thread. Under load, this exhausts the thread pool and tanks performance.</p><p><strong>✅ Benefit:</strong> Eliminates deadlocks and thread pool starvation.</p><p><strong>📌 When to use </strong><strong>async/await all the way:</strong> Always — it&#39;s the only safe pattern.</p><p><strong>🚫 When not to use </strong><strong>.Result:</strong> Never, except in very specific bootstrapping scenarios where you absolutely cannot use async (and even then, use GetAwaiter().GetResult() with extreme care).</p><h3>Rule 8: Use IAsyncEnumerable&lt;T&gt; for Streaming Large Data Sets</h3><h3>❌ Wrong — Loads everything into memory first</h3><pre>[HttpGet(&quot;reports/large&quot;)]<br>public async Task&lt;IActionResult&gt; GetLargeReport()<br>{<br>    var allRows = await _db.Reports.ToListAsync(); // 500k rows in memory!<br>    return Ok(allRows);<br>}</pre><h3>✅ Correct — Streams rows as they’re read</h3><pre>[HttpGet(&quot;reports/large&quot;)]<br>public async IAsyncEnumerable&lt;ReportRow&gt; GetLargeReport(<br>    [EnumeratorCancellation] CancellationToken cancellationToken)<br>{<br>    await foreach (var row in _db.Reports.AsAsyncEnumerable()<br>        .WithCancellation(cancellationToken))<br>    {<br>        yield return row;<br>    }<br>}</pre><p>ASP.NET Core with System.Text.Json natively supports IAsyncEnumerable&lt;T&gt; — it streams JSON to the client as rows arrive, with constant memory usage.</p><p><strong>✅ Benefit:</strong> Constant memory footprint for large result sets; client starts receiving data immediately.</p><p><strong>📌 When to use:</strong> Reports, exports, data feeds, any endpoint returning thousands of rows.</p><p><strong>🚫 When not to use:</strong> Small result sets where the streaming overhead isn’t justified; when the client needs the full collection before doing anything.</p><h3>Rule 9: Handle Exceptions Properly in Async Code</h3><h3>❌ Wrong — Exception is lost</h3><pre>public async Task ProcessAsync()<br>{<br>    try<br>    {<br>        var task = _service.DoWorkAsync(); // not awaited yet<br>        // exception from DoWorkAsync won&#39;t be caught here<br>        await task;<br>    }<br>    catch (Exception ex)<br>    {<br>        _logger.LogError(ex, &quot;Failed&quot;); // may never execute<br>    }<br>}</pre><h3>✅ Correct</h3><pre>public async Task ProcessAsync()<br>{<br>    try<br>    {<br>        await _service.DoWorkAsync(); // await immediately<br>    }<br>    catch (OperationCanceledException)<br>    {<br>        _logger.LogInformation(&quot;Operation was cancelled&quot;);<br>    }<br>    catch (HttpRequestException ex)<br>    {<br>        _logger.LogError(ex, &quot;HTTP call failed&quot;);<br>        throw; // re-throw to let the caller handle it<br>    }<br>    catch (Exception ex)<br>    {<br>        _logger.LogError(ex, &quot;Unexpected failure&quot;);<br>        throw;<br>    }<br>}</pre><p><strong>Handling multiple parallel tasks:</strong></p><pre>// Task.WhenAll wraps all exceptions in an AggregateException<br>try<br>{<br>    await Task.WhenAll(task1, task2, task3);<br>}<br>catch (Exception)<br>{<br>    // Inspect individual task exceptions<br>    var exceptions = new[] { task1, task2, task3 }<br>        .Where(t =&gt; t.IsFaulted)<br>        .Select(t =&gt; t.Exception!.InnerException);<br><br>        foreach (var ex in exceptions)<br>        _logger.LogError(ex, &quot;Task failed&quot;);<br>}</pre><p><strong>✅ Benefit:</strong> No silent failures; proper logging and recovery paths.</p><p><strong>📌 When to use:</strong> Every async call that can realistically throw.</p><p><strong>🚫 When not to use:</strong> Don’t swallow exceptions with empty catch blocks — always log or re-throw.</p><h3>Rule 10: Avoid async Overhead When Not Needed — Skip Async for Pass-Through Methods</h3><h3>❌ Unnecessary async overhead</h3><pre>public async Task&lt;User&gt; GetUserAsync(int id)<br>{<br>    // This method does nothing after the await — no need for async machinery<br>    return await _repository.GetUserAsync(id);<br>}</pre><h3>✅ Correct — Return the Task directly</h3><pre>public Task&lt;User&gt; GetUserAsync(int id)<br>{<br>    // Just forward the Task — no state machine created<br>    return _repository.GetUserAsync(id);<br>}</pre><p><strong>Why does this matter?</strong></p><p>Every async method generates a compiler-created state machine. If your method is simply forwarding a call with no work before or after the await, you&#39;re paying for the state machine for nothing. Just return the Task directly.</p><p><strong>However — important exception:</strong> If you’re inside a try/catch or using block, you <strong>must</strong> use await:</p><pre>// MUST use await here — without it, the using block disposes<br>// the connection before the query completes<br>public async Task&lt;User&gt; GetUserAsync(int id)<br>{<br>    using var connection = _connectionFactory.Create();<br>    return await connection.QueryAsync&lt;User&gt;(id); // correct<br>}</pre><p><strong>✅ Benefit:</strong> Eliminates unnecessary allocations and state machine overhead.</p><p><strong>📌 When to use:</strong> Simple pass-through methods with no try/catch or using blocks.</p><p><strong>🚫 When not to use:</strong> Inside try/catch, using, lock, or when you need to do work after the awaited call.</p><h3>🔀 Async/Await Decision Flowchart</h3><p>Not sure which rule applies to your method? Use this decision flowchart to pick the right pattern every time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*Cwv90udSOwf1opJFEK1EZQ.png" /></figure><h3>Summary Cheat Sheet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C2ajSAGBkvlyQMty3PfDjA.png" /></figure><h3>Final Thoughts</h3><p>Async/await in C# looks simple at first, but there’s a lot going on under the hood. These rules aren’t just coding style — they directly affect how your app performs, how reliable it is, and whether it behaves correctly when your .NET 10 Web API is handling real traffic.</p><p>The single biggest mindset shift: <strong>async isn’t about speed, it’s about scalability.</strong> A single async call isn’t faster than its synchronous counterpart — but a Web API handling 10,000 concurrent requests with async code will massively outperform one using synchronous blocking, because threads aren’t idle, they’re working.</p><p>Apply these rules consistently, and your API will be more resilient, more scalable, and far easier to debug.</p><p><em>Happy coding! 🚀</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b80fd242a10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Unit Testing in .NET 10 Web API (xUnit + Moq) — Full Guide]]></title>
            <link>https://medium.com/@chandrashekharsingh25/learn-unit-testing-in-net-10-web-api-xunit-moq-full-guide-44bc722b8d27?source=rss-796c5dd99155------2</link>
            <guid isPermaLink="false">https://medium.com/p/44bc722b8d27</guid>
            <category><![CDATA[dot-net-core]]></category>
            <category><![CDATA[xunit]]></category>
            <category><![CDATA[moq]]></category>
            <category><![CDATA[dot-net-developers]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Chandrashekhar Singh]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 08:02:32 GMT</pubDate>
            <atom:updated>2026-04-30T08:02:32.757Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By a developer who learned the hard way — so you don’t have to.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bl8QCoSCFZu4TzPPdrRfPQ.png" /></figure><h3>Introduction</h3><p>You just built a shiny new .NET 10 Web API. It works on your machine. You deploy it. Something breaks in production at 2 AM.</p><p>Sound familiar?</p><p>This is exactly where <strong>unit tests</strong> save you. They are small pieces of code that check whether your actual code does what you expect it to do — before it reaches production.</p><p>In this blog, we will go through everything from scratch:</p><ul><li>What is a unit test and why you should write one</li><li>What to be careful about when writing tests</li><li>The <strong>AAA Pattern</strong> (Arrange, Act, Assert)</li><li>Step-by-step setup and real code examples</li></ul><p>Let’s dive in.</p><h3>Why Should You Write Unit Tests?</h3><p>Here are the most important reasons, in plain English:</p><p><strong>1. You catch bugs early</strong> A bug found during development costs almost nothing to fix. A bug found in production can cost your company money, reputation, and sleep.</p><p><strong>2. You can refactor with confidence</strong> If you change how some code works internally, your tests tell you immediately if something broke. Without tests, you are guessing.</p><p><strong>3. Tests act as documentation</strong> A well-written test tells the next developer (or future you) exactly what a function is supposed to do. Better than a comment that nobody reads.</p><p><strong>4. Faster debugging</strong> When a test fails, you know exactly which small piece of code is broken. No need to trace through the whole application.</p><p><strong>5. Prevents regression</strong> A “regression” means something that was working before, broke again. Unit tests catch that before it ships.</p><h3>What to Be Careful About When Writing Unit Tests</h3><p>Before writing a single line of test code, keep these things in mind:</p><p><strong>Test one thing at a time</strong> Each test should verify one specific behavior. If your test is checking three things at once, split it into three tests.</p><p><strong>Tests should be independent</strong> One test should not depend on another test passing first. If test B requires test A to run before it, that is a problem.</p><p><strong>Use meaningful test names</strong> A test named Test1() tells you nothing. A test named GetById_NonExistingId_ReturnsNull() tells you everything.</p><p><strong>Do not test third-party code</strong> You should not write tests for Entity Framework, ASP.NET Core, or any NuGet package. Test your own logic only.</p><p><strong>Keep tests fast</strong> Unit tests should run in milliseconds. If your test is hitting a real database or a real HTTP endpoint, it is an integration test, not a unit test.</p><p><strong>Avoid magic numbers</strong> If you are checking Assert.Equal(42, result.Id), the number 42 should mean something clear in context. Name your test data well.</p><p><strong>Reset state between tests</strong> If two tests share state (like a database), one test’s changes can break another. Use fresh instances for each test, or clean up after each run.</p><h3>The AAA Pattern</h3><p>Every good unit test follows three steps. This is called the <strong>AAA Pattern</strong>:</p><pre>Arrange → Act → Assert</pre><h3>Arrange</h3><p>Set up everything your test needs. Create objects, configure mocks, prepare input data.</p><h3>Act</h3><p>Call the actual method or function you are testing. Just one call — nothing else.</p><h3>Assert</h3><p>Check that the result is what you expected. Did it return the right value? Did it call the right method?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*BYRu1tSfCNHX6sGsJUC-7w.png" /></figure><p>Here is a simple example:</p><pre>[Fact]<br>public async Task GetById_ExistingId_ReturnsProduct()<br>{<br>    // Arrange<br>    var product = new Products { Id = 42, Name = &quot;Keyboard&quot;, Price = 89m, Stock = 15 };<br>    _mockRepo.Setup(r =&gt; r.GetByIdAsync(42)).ReturnsAsync(product);<br><br>    // Act<br>    var result = await _controller.Get(42);<br>    // Assert<br>    var okResult = Assert.IsType&lt;OkObjectResult&gt;(result.Result);<br>    var dto = Assert.IsType&lt;ProductsDto&gt;(okResult.Value);<br>    Assert.Equal(42, dto.Id);<br>    Assert.Equal(&quot;Keyboard&quot;, dto.Name);<br>}</pre><p>See how each section is clearly separated by a comment? That is the AAA pattern in action.</p><h3>Step-by-Step Setup</h3><h3>Step 1 — Create the Test Project</h3><p>In your solution, add a new xUnit test project:</p><pre>dotnet new xunit -n Product.Tests.Unit<br>cd Product.Tests.Unit</pre><h3>Step 2 — Add NuGet Packages</h3><p>You will need these packages:</p><pre>dotnet add package Moq<br>dotnet add package Microsoft.EntityFrameworkCore.InMemory<br>dotnet add package xunit<br>dotnet add package xunit.runner.visualstudio<br>dotnet add package Microsoft.NET.Test.Sdk</pre><ul><li><strong>xUnit</strong> — the test framework</li><li><strong>Moq</strong> — for creating mock (fake) objects</li><li><strong>InMemory</strong> — a fake in-memory database for repository tests</li></ul><h3>Step 3 — Reference Your Main Project</h3><pre>dotnet add reference ../Product.API/Product.API.csproj</pre><h3>Two Kinds of Unit Tests in a Web API</h3><p>In a typical .NET 10 Web API, you will write unit tests for two main layers:</p><ol><li><strong>Controller Tests</strong> — test your API endpoints</li><li><strong>Repository Tests</strong> — test your data access logic</li></ol><p>Let’s look at both.</p><h3>Part 1 — Controller Tests with Mocking</h3><p>The idea here is simple: your controller depends on a repository. Instead of using a real database, you create a <strong>mock</strong> (fake) repository using Moq and tell it what to return.</p><h3>Setting Up the Controller Test Class</h3><pre>public class ProductsControllerTests<br>{<br>    private readonly Mock&lt;IProductRepository&gt; _mockRepo;<br>    private readonly ProductsController _controller;<br><br>    public ProductsControllerTests()<br>    {<br>        _mockRepo = new Mock&lt;IProductRepository&gt;();<br>        _controller = new ProductsController(_mockRepo.Object);<br>    }<br>}</pre><blockquote><strong><em>Important — Primary Constructor vs Regular Constructor</em></strong></blockquote><blockquote><strong>C# 12 introduced primary constructors, which let you write parameters directly on the class declaration like this.</strong></blockquote><pre>// ❌ This looks clean but will NOT work correctly in xUnit<br>public class ProductsControllerTests(Mock&lt;IProductRepository&gt; _mockRepo, ProductsController _controller)<br>{<br>}</pre><blockquote><strong><em>Why does this not work?</em></strong></blockquote><blockquote><em>When you use a primary constructor, the C# compiler does </em><strong><em>not</em></strong><em> automatically promote those parameters into class-level fields. They are only scoped to the constructor — which means your test methods cannot access </em><em>_mockRepo or </em><em>_controller at all. You will either get a compile error or a </em><em>null at runtime.</em></blockquote><blockquote><em>Also, the actual purpose of primary constructors is for </em><strong><em>Dependency Injection</em></strong><em> — where services are registered in a DI container and the framework injects them for you. But </em><em>Mock&lt;T&gt; and </em><em>ProductsController are not registered services anywhere. You create them yourself using </em><em>new. So a primary constructor is simply the wrong tool here.</em></blockquote><blockquote><strong><em>The correct approach — Regular Constructor:</em></strong></blockquote><pre>// ✅ Correct approach<br>public class ProductsControllerTests<br>{<br>    private readonly Mock&lt;IProductRepository&gt; _mockRepo;<br>    private readonly ProductsController _controller;<br><br>    public ProductsControllerTests()<br>    {<br>        _mockRepo = new Mock&lt;IProductRepository&gt;();<br>        _controller = new ProductsController(_mockRepo.Object);<br>    }<br>}</pre><blockquote><em>In a regular constructor, you create the objects yourself and store them in </em><em>private readonly fields — so every test method in the class can access them. This is the correct and clean way to set up a test class in xUnit.</em></blockquote><h3>Test 1 — Get All Products (Happy Path)</h3><pre>[Fact]<br>public async Task GetAll_ReturnsAllProducts()<br>{<br>    // Arrange<br>    var products = new List&lt;Products&gt;<br>    {<br>        new() { Id = 1, Name = &quot;Laptop&quot;, Price = 1200m, Stock = 10 },<br>        new() { Id = 2, Name = &quot;Mouse&quot;,  Price = 25m,   Stock = 50 }<br>    };<br><br>   _mockRepo.Setup(r =&gt; r.GetAllAsync())<br>             .ReturnsAsync(products);<br>    // Act<br>    var result = await _controller.GetAll();<br>    // Assert<br>    var okResult = Assert.IsType&lt;OkObjectResult&gt;(result.Result);<br>    var dtos = Assert.IsType&lt;List&lt;ProductsDto&gt;&gt;(okResult.Value);<br>    Assert.Equal(2, dtos.Count);<br>    Assert.Equal(&quot;Laptop&quot;, dtos[0].Name);<br>}</pre><p><strong>What is happening here?</strong></p><ul><li>We fake the repository to return two products</li><li>We call the controller’s GetAll() method</li><li>We verify that the response is 200 OK and the data is mapped correctly</li></ul><h3>Test 2 — Get By ID When Product Does Not Exist</h3><pre>[Fact]<br>public async Task Get_NonExistingId_ReturnsNotFound()<br>{<br>    // Arrange<br>    _mockRepo.Setup(r =&gt; r.GetByIdAsync(999)).ReturnsAsync((Products?)null);<br><br>   // Act<br>    var result = await _controller.Get(999);<br>    // Assert<br>    Assert.IsType&lt;NotFoundResult&gt;(result.Result);<br>}</pre><p>This is the <strong>sad path</strong> test. Always test what happens when things go wrong, not just when they go right.</p><h3>Test 3 — Create Product with Invalid Data (Theory Test)</h3><p>[Theory] lets you run the same test with multiple sets of inputs:</p><pre>[Theory]<br>[InlineData(&quot;&quot;, 100, 5)]        // empty name<br>[InlineData(&quot;TV&quot;, -50, 10)]      // negative price<br>[InlineData(&quot;Phone&quot;, 500, -3)]   // negative stock<br>public async Task Create_InvalidData_ReturnsBadRequest(string name, decimal price, int stock)<br>{<br>    // Arrange<br>    var invalidDto = new CreateProductsDto(name, price, stock);<br>    <br>    // Act<br>    var result = await _controller.Create(invalidDto);<br>    // Assert<br>    Assert.IsType&lt;BadRequestObjectResult&gt;(result.Result);<br>}</pre><p>Three different invalid inputs, one test method. Clean and efficient.</p><h3>Test 4 — Verify a Method Was Actually Called</h3><pre>[Fact]<br>public async Task Update_ExistingProduct_ReturnsNoContent()<br>{<br>    // Arrange<br>    var updateDto = new UpdateProductsDto(&quot;New Chair&quot;, null, 15);<br><br>  _mockRepo.Setup(r =&gt; r.GetByIdAsync(5))<br>             .ReturnsAsync(new Products { Id = 5, Name = &quot;Old Chair&quot;, Price = 45m, Stock = 20 });<br>    _mockRepo.Setup(r =&gt; r.UpdateAsync(5, updateDto))<br>             .Returns(Task.CompletedTask);<br>    // Act<br>    var result = await _controller.Update(5, updateDto);<br>    // Assert<br>    Assert.IsType&lt;NoContentResult&gt;(result);<br>    _mockRepo.Verify(r =&gt; r.UpdateAsync(5, updateDto), Times.Once());<br>}</pre><p>_mockRepo.Verify(...) is a powerful feature of Moq. It checks that UpdateAsync was called exactly once with the right arguments. This ensures your controller is actually doing its job, not just returning the right status code by accident.</p><h3>Part 2 — Repository Tests with In-Memory Database</h3><p>For repository tests, you want to test the actual database logic. But you do not want to talk to a real SQL Server. That is where <strong>EF Core’s InMemory provider</strong> comes in.</p><h3>Step 1 — Create a Test Fixture</h3><p>A fixture sets up the database once and seeds test data. It is shared across tests in the same class:</p><pre>public class ProductRepositoryTestFixture : IDisposable<br>{<br>    public ProductDbContext Context { get; }<br>    <br>    public ProductRepositoryTestFixture()<br>    {<br>        var databaseName = Guid.NewGuid().ToString(); // unique per test run<br>        var options = new DbContextOptionsBuilder&lt;ProductDbContext&gt;()<br>            .UseInMemoryDatabase(databaseName)<br>            .Options;<br>        Context = new ProductDbContext(options);<br>        SeedData();<br>    }<br>    private void SeedData()<br>    {<br>        if (!Context.Products.Any())<br>        {<br>            Context.Products.AddRange(<br>                new Products { Id = 1, Name = &quot;Laptop&quot;, Price = 1200m, Stock = 10 },<br>                new Products { Id = 2, Name = &quot;Mouse&quot;, Price = 25m, Stock = 50 },<br>                new Products { Id = 3, Name = &quot;Keyboard&quot;, Price = 89m, Stock = 15 }<br>            );<br>            Context.SaveChanges();<br>        }<br>    }<br>    public void Dispose() =&gt; Context.Dispose();<br>}</pre><blockquote><strong><em>Key detail:</em></strong><em> </em><em>Guid.NewGuid().ToString() gives each test run a fresh database name. This prevents tests from interfering with each other.</em></blockquote><h3>Step 2 — Use the Fixture in Tests</h3><pre>public class ProductRepositoryTests : IClassFixture&lt;ProductRepositoryTestFixture&gt;<br>{<br>    private readonly ProductRepositoryTestFixture _fixture;<br>    private readonly IProductRepository _repository;<br>    <br>    public ProductRepositoryTests(ProductRepositoryTestFixture fixture)<br>    {<br>        _fixture = fixture;<br>        _repository = new ProductRepository(_fixture.Context);<br>    }<br>}</pre><p>IClassFixture&lt;T&gt; tells xUnit to create the fixture once for the whole test class and inject it.</p><h3>Test — GetById Returns Correct Product</h3><pre>[Fact]<br>public async Task GetByIdAsync_ExistingId_ReturnsProduct()<br>{<br>    // Act<br>    var result = await _repository.GetByIdAsync(2);<br><br>    // Assert<br>    Assert.NotNull(result);<br>    Assert.Equal(2, result.Id);<br>    Assert.Equal(&quot;Mouse&quot;, result.Name);<br>    Assert.Equal(25m, result.Price);<br>}</pre><h3>Test — Add a New Product</h3><pre>[Fact]<br>public async Task AddAsync_AddsProductAndSetsId()<br>{<br>    // Arrange<br>    var newProduct = new Products { Name = &quot;Monitor&quot;, Price = 299m, Stock = 8 };<br><br>    // Act<br>    var added = await _repository.AddAsync(newProduct);<br>    // Assert<br>    Assert.NotEqual(0, added.Id);  // ID should be auto-generated<br>    Assert.Equal(&quot;Monitor&quot;, added.Name);<br>    var fromDb = await _fixture.Context.Products.FindAsync(added.Id);<br>    Assert.NotNull(fromDb);<br>    Assert.Equal(299m, fromDb.Price);<br>}</pre><h3>Test — Delete a Product</h3><pre>[Fact]<br>public async Task DeleteAsync_RemovesProduct()<br>{<br>    // Arrange<br>    var product = await _repository.GetByIdAsync(3);<br>    Assert.NotNull(product);<br><br>    // Act<br>    await _repository.DeleteAsync(product.Id);<br>    // Assert<br>    var deleted = await _repository.GetByIdAsync(3);<br>    Assert.Null(deleted);<br>}</pre><h3>Running Your Tests</h3><p>From the terminal:</p><pre>dotnet test</pre><p>Or in Visual Studio / Rider, open the <strong>Test Explorer</strong> and click <strong>Run All</strong>.</p><p>You will see green (pass) or red (fail) for each test, along with the reason for any failure.</p><h3>Quick Reference — Common xUnit Assertions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWk4_rAmMqXD2gXce0JoVQ.png" /></figure><h3>Common Moq Patterns</h3><pre>// Return a value<br>_mockRepo.Setup(r =&gt; r.GetByIdAsync(1)).ReturnsAsync(product);<br><br>// Return null<br>_mockRepo.Setup(r =&gt; r.GetByIdAsync(999)).ReturnsAsync((Products?)null);<br>// Return nothing (void/Task)<br>_mockRepo.Setup(r =&gt; r.DeleteAsync(1)).Returns(Task.CompletedTask);<br>// Match any argument<br>_mockRepo.Setup(r =&gt; r.AddAsync(It.IsAny&lt;Products&gt;())).ReturnsAsync(savedProduct);<br>// Verify a method was called<br>_mockRepo.Verify(r =&gt; r.UpdateAsync(5, dto), Times.Once());<br>// Verify a method was never called<br>_mockRepo.Verify(r =&gt; r.DeleteAsync(It.IsAny&lt;int&gt;()), Times.Never());</pre><h3>Summary</h3><p>Here is everything you learned in one place:</p><ul><li>Unit tests catch bugs before production and let you refactor safely</li><li>Always follow the <strong>AAA Pattern</strong>: Arrange → Act → Assert</li><li>Test both the <strong>happy path</strong> (things go right) and the <strong>sad path</strong> (things go wrong)</li><li>Use <strong>Moq</strong> to fake dependencies in controller tests</li><li>Use <strong>EF Core InMemory</strong> to test repositories without a real database</li><li>Use [Fact] for single tests and [Theory] with [InlineData] for multiple inputs</li><li>Use IClassFixture&lt;T&gt; to share test setup across multiple tests</li><li>Name your tests clearly: MethodName_Scenario_ExpectedResult</li></ul><p>The full source code is available here: <a href="https://github.com/CSSinghNet/Product.API"><strong>https://github.com/CSSinghNet/Product.API</strong></a></p><h3>Final Thought</h3><p>Writing unit tests feels slow at first. But every test you write is a safety net for the future. The cost of writing a test is small. The cost of a production bug is not.</p><p>Start small. Test the most critical parts of your API first. Build the habit. Your future self — and your teammates — will thank you.</p><p>Happy testing! 🧪</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44bc722b8d27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular @defer Lazy Loading Guide (2026) — Build Faster Apps Easily]]></title>
            <link>https://medium.com/@chandrashekharsingh25/angular-defer-lazy-loading-guide-2026-build-faster-apps-easily-ddcbd1fd71e5?source=rss-796c5dd99155------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddcbd1fd71e5</guid>
            <category><![CDATA[lazy-loadin]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-lazy-loading]]></category>
            <dc:creator><![CDATA[Chandrashekhar Singh]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 05:36:42 GMT</pubDate>
            <atom:updated>2026-04-29T05:36:42.726Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WDUo2z8ScApKL88X9PbfnA.png" /></figure><blockquote>How Angular’s declarative deferral block is redefining performance optimization — and why you should be using it today.</blockquote><h3>The Problem Every Angular Developer Knows</h3><p>You’ve built a feature-rich dashboard. Charts, data tables, comment threads, rich text editors — all packed into a single route. The page loads… and loads… and loads. Your Lighthouse score weeps. Your users bounce.</p><p>The culprit? <strong>Everything renders at once, whether the user needs it or not.</strong></p><p>For years, Angular developers worked around this with a patchwork of techniques — manual loadChildren, *ngIf guards, IntersectionObserver hacks. They worked, but they were verbose, error-prone, and easy to get wrong.</p><p>Angular 17 changed the game with @defer.</p><h3>What Is @defer?</h3><p>@defer is a <strong>built-in Angular template block</strong> that defers the loading and rendering of a chunk of your template — including its component, directives, and pipes — until a specific trigger condition is met.</p><p>It ships as part of Angular’s new control flow syntax alongside @if, @for, and @switch. No modules to import. No boilerplate. Just declare it in your template and Angular handles the rest.</p><pre>@defer {<br>  &lt;heavy-dashboard-chart /&gt;<br>}</pre><p>That single block tells Angular: <em>“Don’t download or render this component until it’s actually needed.”</em></p><h3>Why @defer Is a Big Deal in Modern Angular</h3><h3>1. Zero-config code splitting</h3><p>When you wrap a component in @defer, Angular&#39;s compiler <strong>automatically splits it into a separate JavaScript chunk</strong>. You don&#39;t touch webpack.config.js. You don&#39;t set up dynamic imports manually. The compiler does it.</p><h3>2. It’s declarative</h3><p>The “what” and “when” of lazy loading live right in your template, next to the component being deferred. Future-you (and your teammates) will thank present-you.</p><h3>3. Built-in UX states</h3><p>@defer ships with companion blocks for handling every loading state gracefully:</p><pre>@defer (on viewport) {<br>  &lt;analytics-chart /&gt;<br>} @loading {<br>  &lt;skeleton-loader /&gt;<br>} @placeholder {<br>  &lt;div class=&quot;chart-placeholder&quot;&gt;Chart loads when visible&lt;/div&gt;<br>} @error {<br>  &lt;p&gt;Failed to load chart. Please refresh.&lt;/p&gt;<br>}</pre><ul><li><strong>@placeholder</strong> — shown <em>before</em> the trigger fires (no download yet)</li><li><strong>@loading</strong> — shown <em>while</em> the chunk is downloading</li><li><strong>@error</strong> — shown if the download or render fails</li></ul><h3>4. No Zone.js gotchas</h3><p>@defer works perfectly with standalone components and Angular&#39;s new zoneless change detection. It&#39;s designed for the future of the framework.</p><h3>What Problem Does It Solve?</h3><p>Problem Without @defer With @defer Large initial bundle Everything downloaded upfront Only what&#39;s needed at load Slow Time to Interactive Full render on every route Critical path only Off-screen components Rendered but invisible Never parsed until needed Loading state management Manual isLoading flags Built-in @loading block Code splitting setup Manual dynamic imports Automatic via compiler</p><p>The core fix: <strong>stop paying the cost of components the user hasn’t asked for yet.</strong></p><h3>The Old Angular Workaround (Pre-@defer)</h3><p>Before Angular 17, there were three common approaches — all more painful than @defer.</p><h3>Approach 1: Route-level lazy loading with loadChildren</h3><pre>const routes: Routes = [<br>  {<br>    path: &#39;dashboard&#39;,<br>    loadChildren: () =&gt;<br>      import(&#39;./dashboard/dashboard.module&#39;).then(m =&gt; m.DashboardModule)<br>  }<br>];</pre><p><strong>Limitation:</strong> This only works at the <em>route</em> level. You can’t lazily load a single component <em>within</em> a page.</p><h3>Approach 2: Manual dynamic import with *ngIf</h3><pre>// component.ts<br>heavyComponent: Type&lt;any&gt; | null = null;<br><br>async loadChart() {<br>  const { HeavyChartComponent } = await import(&#39;./heavy-chart/heavy-chart.component&#39;);<br>  this.heavyComponent = HeavyChartComponent;<br>}</pre><pre>&lt;ng-container *ngComponentOutlet=&quot;heavyComponent&quot; /&gt;</pre><p><strong>Limitation:</strong> Verbose, imperative, and you’re manually wiring up the loading state, error handling, and trigger logic every single time.</p><h3>Approach 3: IntersectionObserver directive</h3><pre>@Directive({ selector: &#39;[lazyLoad]&#39; })<br>export class LazyLoadDirective implements AfterViewInit {<br>  @Output() visible = new EventEmitter&lt;void&gt;();<br><br>constructor(private el: ElementRef) {}<br>  ngAfterViewInit() {<br>    const observer = new IntersectionObserver(([entry]) =&gt; {<br>      if (entry.isIntersecting) {<br>        this.visible.emit();<br>        observer.disconnect();<br>      }<br>    });<br>    observer.observe(this.el.nativeElement);<br>  }<br>}</pre><p><strong>Limitation:</strong> You’d still combine this with approach 2 for actual lazy loading, and now you have a custom directive to maintain on top of everything else.</p><p>@defer replaces all three with a single, readable template block.</p><h3>How to Implement @defer — Step by Step</h3><h3>Prerequisites</h3><ul><li>Angular 17+ (standalone components recommended)</li><li>The deferred component must be a <strong>standalone component</strong></li></ul><h3>Basic syntax</h3><pre>@defer {<br>  &lt;my-component /&gt;<br>}</pre><h3>With all companion blocks</h3><pre>@defer (on viewport; prefetch on idle) {<br>  &lt;sales-report-table /&gt;<br>} @loading (minimum 300ms) {<br>  &lt;app-spinner /&gt;<br>} @placeholder (minimum 500ms) {<br>  &lt;div class=&quot;placeholder-box&quot;&gt;&lt;/div&gt;<br>} @error {<br>  &lt;p&gt;Could not load report. &lt;button (click)=&quot;retry()&quot;&gt;Retry&lt;/button&gt;&lt;/p&gt;<br>}</pre><p>The minimum parameter on @loading and @placeholder prevents a jarring flash if the load is very fast.</p><h3>Triggers — The Real Power</h3><p>Triggers are what make @defer truly flexible. You can combine <strong>when to render</strong> (on) with <strong>when to prefetch</strong> (prefetch on).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6qSfSvssEIr00fesTrdlw.png" /></figure><h3>on idle</h3><p>on idle loads the content <strong>when the browser is free</strong> (not busy with important tasks).</p><p>👉 It uses <strong>requestIdleCallback </strong>internally.</p><pre>@defer (on idle) {<br>  &lt;recommendation-sidebar /&gt;<br>}</pre><p><strong>Use case:</strong> Use it for things that are <strong>not important for initial page load</strong>.</p><p>Examples:</p><ul><li>Recommendations section</li><li>Ads</li><li>Analytics widgets</li><li>Extra UI features</li></ul><h3>on viewport</h3><p>on viewport loads the content <strong>when it comes into the user’s screen (visible area).</strong></p><p>👉 Angular automatically uses <strong>IntersectionObserver</strong> for this.</p><pre>@defer (on viewport) {<br>  &lt;comments-section /&gt;<br>} @placeholder {<br>  &lt;div style=&quot;height: 400px;&quot;&gt;&lt;/div&gt;<br>}</pre><p><strong>Use case:</strong> Use it for content that is <strong>below the fold</strong> (not visible at first).</p><p>Examples:</p><ul><li>Comments section</li><li>Related articles</li><li>Product reviews</li><li>Footer content</li></ul><h3>on interaction</h3><p>on interaction loads the content <strong>only when the user interacts</strong> with it<br> (like click, focus, etc.).</p><pre>@defer (on interaction) {<br>  &lt;rich-text-editor /&gt;<br>} @placeholder {<br>  &lt;div class=&quot;editor-placeholder&quot;&gt;Click to start editing...&lt;/div&gt;<br>}</pre><p><strong>Use case:</strong> Use it for heavy UI components that <strong>users may or may not use</strong>.</p><p>Examples:</p><ul><li>Rich text editors</li><li>Date pickers</li><li>Color pickers</li><li>Advanced filters</li></ul><h3>on hover</h3><p>on hover loads the content <strong>when the user moves the mouse over it</strong>.</p><pre>@defer (on hover) {<br>  &lt;user-profile-popover [userId]=&quot;user.id&quot; /&gt;<br>} @placeholder {<br>  &lt;span class=&quot;username&quot;&gt;{{ user.name }}&lt;/span&gt;<br>}</pre><p><strong>Use case:</strong> Use it for UI elements that appear <strong>on hover</strong>.</p><p>Examples:</p><ul><li>Tooltips</li><li>Popovers</li><li>Preview cards</li></ul><h3>on timer(delay)</h3><p>on timer loads the content <strong>after a fixed delay</strong>.</p><pre>@defer (on timer(3000ms)) {<br>  &lt;cookie-consent-banner /&gt;<br>}</pre><p><strong>Use case:</strong> Use it when you want to <strong>delay something intentionally</strong>.</p><p>Examples:</p><ul><li>Cookie banners</li><li>Survey popups</li><li>Upsell modals</li></ul><h3>when (condition)</h3><p>when loads the content <strong>only when a condition becomes true</strong>.</p><pre>// component.ts<br>showAdvancedFilters = false;<br></pre><pre>&lt;button (click)=&quot;showAdvancedFilters = true&quot;&gt;Show Advanced Filters&lt;/button&gt;<br><br>@defer (when showAdvancedFilters) {<br>  &lt;advanced-filter-panel /&gt;<br>} @placeholder {<br>  &lt;p&gt;Advanced filters hidden&lt;/p&gt;<br>}</pre><p><strong>Use case:</strong> Use it when loading depends on <strong>logic or state</strong>.</p><p>Examples:</p><ul><li>Feature flags</li><li>User role-based UI</li><li>Toggle sections (show/hide)</li></ul><h3>Prefetching</h3><p>Prefetching means <strong>downloading the component early</strong>, but <strong>not showing it yet</strong>.</p><pre>@defer (on interaction; prefetch on idle) {<br>  &lt;video-player [src]=&quot;videoUrl&quot; /&gt;<br>} @placeholder {<br>  &lt;img [src]=&quot;thumbnail&quot; alt=&quot;Play video&quot; /&gt;<br>}</pre><p>Here: How it works?</p><ul><li>JS file gets downloaded in background (e.g., during idle time)</li><li>UI renders later when trigger happens</li></ul><h3>When to use it?</h3><p>Use it when you want:</p><ul><li>Faster interaction later</li><li>Smooth user experience</li></ul><h3>Real-World Use Case: E-Commerce Product Page</h3><p>Here’s a realistic product page that uses @defer strategically across multiple sections:</p><pre>&lt;!-- product-page.component.html --&gt;<br><br>&lt;!-- 1. Hero section - renders immediately, no defer --&gt;<br>&lt;product-hero [product]=&quot;product&quot; /&gt;<br>&lt;!-- 2. Image gallery - defer until idle, it&#39;s below the fold on mobile --&gt;<br>@defer (on idle; prefetch on viewport) {<br>  &lt;product-image-gallery [images]=&quot;product.images&quot; /&gt;<br>} @loading {<br>  &lt;gallery-skeleton /&gt;<br>} @placeholder {<br>  &lt;img [src]=&quot;product.images[0]&quot; alt=&quot;Product&quot; /&gt;<br>}<br>&lt;!-- 3. Reviews - defer until user scrolls down --&gt;<br>@defer (on viewport) {<br>  &lt;product-reviews [productId]=&quot;product.id&quot; /&gt;<br>} @placeholder {<br>  &lt;div class=&quot;reviews-placeholder&quot; style=&quot;min-height: 300px;&quot;&gt;<br>    &lt;h3&gt;Customer Reviews&lt;/h3&gt;<br>  &lt;/div&gt;<br>} @loading {<br>  &lt;review-skeleton [count]=&quot;3&quot; /&gt;<br>}<br>&lt;!-- 4. Rich text description editor (admin only) - defer until interaction --&gt;<br>@if (isAdmin) {<br>  @defer (on interaction; when isEditMode) {<br>    &lt;rich-text-editor [(content)]=&quot;product.description&quot; /&gt;<br>  } @placeholder {<br>    &lt;div (click)=&quot;isEditMode = true&quot; class=&quot;description-preview&quot;&gt;<br>      {{ product.description | truncate:200 }}<br>      &lt;span class=&quot;edit-hint&quot;&gt;Click to edit&lt;/span&gt;<br>    &lt;/div&gt;<br>  }<br>}<br>&lt;!-- 5. Recommendations - fully deferred, low priority --&gt;<br>@defer (on idle) {<br>  &lt;product-recommendations [category]=&quot;product.category&quot; /&gt;<br>} @placeholder {<br>  &lt;div style=&quot;min-height: 200px;&quot;&gt;&lt;/div&gt;<br>}</pre><p><strong>What this achieves:</strong></p><ul><li>The hero renders instantly — critical path is tiny</li><li>The gallery downloads lazily but prefetches as the user nears it — feels instant</li><li>Reviews never load for users who don’t scroll — saves bandwidth for most mobile sessions</li><li>The rich editor (a heavy Quill.js bundle) only downloads if an admin clicks edit</li><li>Recommendations are lowest priority and never block anything</li></ul><p>This single page went from a 2.1 MB initial bundle to a 380 KB critical bundle in a real-world refactor. Everything else loads exactly when needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1f2NBVwJRShHRpqX9slVw.png" /></figure><h3>Important Things to Remember</h3><p><strong>1. The deferred component must be standalone</strong> NgModule-based components cannot be deferred. If you’re still on modules, migrate the component to standalone first.</p><p><strong>2. </strong><strong>@placeholder needs a minimum height</strong> If your placeholder has zero height, on viewport will fire immediately because a zero-height element is technically &quot;in the viewport.&quot; Always give your placeholder a realistic height.</p><p><strong>3. Don’t defer everything</strong> Defer components that are heavy <em>and</em> not immediately visible. Don’t defer things like navbar or hero section,<br> otherwise you may see flickers or layout issues.</p><p><strong>4. SSR considerations</strong> On Server-Side Rendering, @defer blocks render their @placeholder content by default. This is usually what you want, but be intentional about what your placeholder looks like for SEO-sensitive content.</p><h3>Summary</h3><p>@defer is one of the most impactful developer experience improvements Angular has shipped in years. It takes a pattern that previously required five different moving parts — dynamic imports, *ngIf, custom directives, manual state flags, and webpack config — and collapses it into a single, readable, declarative template block.</p><p>If you’re on Angular 17+, there’s almost no reason <em>not</em> to reach for @defer on any component that:</p><ul><li>Lives below the fold</li><li>Is only shown conditionally</li><li>Is heavy (charts, editors, maps, video players)</li><li>Is an admin-only or power-user feature</li></ul><p>The performance wins are real. The code is cleaner. And the user experience — with proper @placeholder and @loading states — is smoother than anything the old workarounds could produce.</p><p>Start with on viewport and on idle. Add prefetch on idle where snappiness matters. Use when for condition-based control. And watch your bundle sizes drop.</p><p>The full source code is available here: <a href="https://github.com/CSSinghNet/defer-demo"><strong>https://github.com/CSSinghNet/defer-demo</strong></a></p><p><em>Found this useful? 👏 Give a clap and follow for more deep-dives into modern Angular patterns, performance optimization, and real-world architecture.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddcbd1fd71e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Entity Framework Core + SQL Server in .NET 8 Web API — Complete Guide]]></title>
            <link>https://medium.com/@chandrashekharsingh25/entity-framework-core-sql-server-in-net-8-web-api-complete-guide-e4d52c05db29?source=rss-796c5dd99155------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4d52c05db29</guid>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[sql-server]]></category>
            <dc:creator><![CDATA[Chandrashekhar Singh]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 15:31:27 GMT</pubDate>
            <atom:updated>2026-04-24T15:31:27.243Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UApvwtMlemnJEMsqP_M46w.png" /></figure><p><em>A practical, no-fluff guide to using EF Core the right way</em></p><p>If you&#39;ve been building .NET Web APIs for a while, you&#39;ve almost certainly heard of Entity Framework Core. It&#39;s Microsoft&#39;s official ORM (Object-Relational Mapper) for .NET, and it&#39;s genuinely one of the best tools in the ecosystem when used correctly.</p><p>But <strong>&quot;<em>when used correctly</em>&quot;</strong> is doing a lot of heavy lifting in that sentence.</p><p>EF Core can save you hundreds of hours of boilerplate SQL. It can also silently destroy your app&#39;s performance if you don&#39;t understand what&#39;s happening under the hood. This guide covers both sides of that coin — how to set it up properly in a .NET 8 Web API, which methods to actually use, the lazy vs eager loading debate, and the notorious N+1 problem that has embarrassed many developers in production.</p><p>Let&#39;s get into it.</p><h3>What Is Entity Framework Core, Really?</h3><p>EF Core is an ORM — it maps your C# classes (called <strong>entities</strong>) to database tables and lets you query and manipulate data using LINQ instead of raw SQL. It translates your C# code into SQL at runtime and handles the round-trip back to objects.</p><p>It&#39;s not magic, though. It&#39;s a translation layer. And like any translator, it sometimes produces awkward output if you don&#39;t give it clear instructions.</p><h3>Integration — Setting It Up in .NET 8 Web API</h3><h3>Step 1: Install the NuGet Packages</h3><p>You&#39;ll need two packages for SQL Server:</p><pre>dotnet add package Microsoft.EntityFrameworkCore.SqlServer<br>dotnet add package Microsoft.EntityFrameworkCore.Tools</pre><p>If you want to scaffold migrations from the CLI:</p><pre>dotnet add package Microsoft.EntityFrameworkCore.Design</pre><h3>Step 2: Create Your Entities</h3><p>Think of entities as plain C# classes that represent your database tables.</p><pre>public class Author<br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; } = string.Empty;<br>    public string Email { get; set; } = string.Empty;<br>    public ICollection&lt;Post&gt; Posts { get; set; } = new List&lt;Post&gt;();<br>}<br><br>public class Post<br>{<br>    public int Id { get; set; }<br>    public string Title { get; set; } = string.Empty;<br>    public string Content { get; set; } = string.Empty;<br>    public DateTime CreatedAt { get; set; }<br>    public int AuthorId { get; set; }<br>    public Author Author { get; set; } = null!;<br>    public ICollection&lt;Comment&gt; Comments { get; set; } = new List&lt;Comment&gt;();<br>}<br><br>public class Comment<br>{<br>    public int Id { get; set; }<br>    public string Body { get; set; } = string.Empty;<br>    public int PostId { get; set; }<br>    public Post Post { get; set; } = null!;<br>}</pre><h3>Step 3: Create the DbContext</h3><p>The DbContext is the heart of EF Core. It&#39;s how you interact with the database.</p><pre>public class AppDbContext : DbContext<br>{<br>    public AppDbContext(DbContextOptions&lt;AppDbContext&gt; options) : base(options) { }<br><br>    public DbSet&lt;Author&gt; Authors { get; set; }<br>    public DbSet&lt;Post&gt; Posts { get; set; }<br>    public DbSet&lt;Comment&gt; Comments { get; set; }<br><br>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        modelBuilder.Entity&lt;Author&gt;(entity =&gt;<br>        {<br>            entity.HasKey(a =&gt; a.Id);<br>            entity.Property(a =&gt; a.Name).IsRequired().HasMaxLength(100);<br>            entity.Property(a =&gt; a.Email).IsRequired().HasMaxLength(200);<br>            entity.HasMany(a =&gt; a.Posts)<br>                  .WithOne(p =&gt; p.Author)<br>                  .HasForeignKey(p =&gt; p.AuthorId)<br>                  .OnDelete(DeleteBehavior.Cascade);<br>        });<br><br>        modelBuilder.Entity&lt;Post&gt;(entity =&gt;<br>        {<br>            entity.HasKey(p =&gt; p.Id);<br>            entity.Property(p =&gt; p.Title).IsRequired().HasMaxLength(300);<br>            entity.HasMany(p =&gt; p.Comments)<br>                  .WithOne(c =&gt; c.Post)<br>                  .HasForeignKey(c =&gt; c.PostId)<br>                  .OnDelete(DeleteBehavior.Cascade);<br>        });<br>    }<br>}</pre><h3>Step 4: Register EF Core in Program.cs</h3><pre>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddDbContext&lt;AppDbContext&gt;(options =&gt;<br>    options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));<br><br>builder.Services.AddControllers();</pre><h3>Step 5: Connection String in appsettings.json</h3><pre>{<br>  &quot;ConnectionStrings&quot;: {<br>    &quot;DefaultConnection&quot;: &quot;Server=localhost;Database=BlogDb;Trusted_Connection=True;TrustServerCertificate=True;&quot;<br>  }<br>}</pre><h3>Step 6: Run Migrations</h3><pre>dotnet ef migrations add InitialCreate<br>dotnet ef database update</pre><p>That&#39;s it — EF Core now manages your schema.</p><h3>Implementation — Repository Pattern with EF Core</h3><p>While you can inject AppDbContext directly into controllers, using a repository pattern keeps things cleaner and testable.</p><pre>public interface IPostRepository<br>{<br>    Task&lt;IEnumerable&lt;Post&gt;&gt; GetAllAsync();<br>    Task&lt;Post?&gt; GetByIdAsync(int id);<br>    Task&lt;Post&gt; CreateAsync(Post post);<br>    Task UpdateAsync(Post post);<br>    Task DeleteAsync(int id);<br>}<br><br>public class PostRepository : IPostRepository<br>{<br>    private readonly AppDbContext _context;<br><br>    public PostRepository(AppDbContext context)<br>    {<br>        _context = context;<br>    }<br><br>    public async Task&lt;IEnumerable&lt;Post&gt;&gt; GetAllAsync()<br>    {<br>        return await _context.Posts<br>            .Include(p =&gt; p.Author)<br>            .Include(p =&gt; p.Comments)<br>            .AsNoTracking()<br>            .ToListAsync();<br>    }<br><br>    public async Task&lt;Post?&gt; GetByIdAsync(int id)<br>    {<br>        return await _context.Posts<br>            .Include(p =&gt; p.Author)<br>            .Include(p =&gt; p.Comments)<br>            .FirstOrDefaultAsync(p =&gt; p.Id == id);<br>    }<br><br>    public async Task&lt;Post&gt; CreateAsync(Post post)<br>    {<br>        post.CreatedAt = DateTime.UtcNow;<br>        _context.Posts.Add(post);<br>        await _context.SaveChangesAsync();<br>        return post;<br>    }<br><br>    public async Task UpdateAsync(Post post)<br>    {<br>        _context.Posts.Update(post);<br>        await _context.SaveChangesAsync();<br>    }<br><br>    public async Task DeleteAsync(int id)<br>    {<br>        var post = await _context.Posts.FindAsync(id);<br>        if (post is not null)<br>        {<br>            _context.Posts.Remove(post);<br>            await _context.SaveChangesAsync();<br>        }<br>    }<br>}</pre><p>Register it in Program.cs:</p><pre>builder.Services.AddScoped&lt;IPostRepository, PostRepository&gt;();</pre><h3>Methods You Actually Use in EF Core</h3><p>Here&#39;s a practical breakdown of the methods you&#39;ll reach for daily.</p><h3>Querying</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUStDu9rZb4_EfBjjXgBCg.png" /></figure><h3>Writing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_OoeOredQAw5fTKNknDMg.png" /></figure><h3>Relationships</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v4uQxt4uggSA1lr_XSsOQw.png" /></figure><h3>Example — Pagination with Projection</h3><pre>public async Task&lt;IEnumerable&lt;PostSummaryDto&gt;&gt; GetPagedAsync(int page, int pageSize)<br>{<br>    return await _context.Posts<br>        .OrderByDescending(p =&gt; p.CreatedAt)<br>        .Skip((page - 1) * pageSize)<br>        .Take(pageSize)<br>        .Select(p =&gt; new PostSummaryDto<br>        {<br>            Id = p.Id,<br>            Title = p.Title,<br>            AuthorName = p.Author.Name,<br>            CommentCount = p.Comments.Count<br>        })<br>        .AsNoTracking()<br>        .ToListAsync();<br>}</pre><h3>Lazy Loading vs Eager Loading</h3><p>This is one of the most misunderstood topics in EF Core. Let&#39;s settle it clearly.</p><h3>Eager Loading</h3><p>With eager loading, you tell EF Core upfront which related data you want. It fetches everything in a single SQL query using JOINs.</p><pre>var posts = await _context.Posts<br>    .Include(p =&gt; p.Author)<br>    .Include(p =&gt; p.Comments)<br>    .ToListAsync();</pre><p><strong>One query. Done.</strong></p><p>You can go deeper with ThenInclude:</p><pre>var authors = await _context.Authors<br>    .Include(a =&gt; a.Posts)<br>        .ThenInclude(p =&gt; p.Comments)<br>    .ToListAsync();</pre><p><strong>Use eager loading when:</strong> You know ahead of time that you&#39;ll need the related data. Most API responses fall into this category.</p><h3>Lazy Loading</h3><p>With lazy loading, related data is loaded automatically the first time you access a navigation property — even if you didn&#39;t ask for it.</p><p>To enable it, install the proxy package:</p><pre>dotnet add package Microsoft.EntityFrameworkCore.Proxies</pre><p>Configure it:</p><pre>builder.Services.AddDbContext&lt;AppDbContext&gt;(options =&gt;<br>    options.UseSqlServer(connectionString)<br>           .UseLazyLoadingProxies());</pre><p>Make navigation properties virtual:</p><pre>public virtual ICollection&lt;Post&gt; Posts { get; set; }</pre><p>Now when you do this:</p><pre>var author = await _context.Authors.FindAsync(1);<br>var postCount = author.Posts.Count; // triggers a separate SQL query here</pre><p>EF Core silently fires another query to load Posts.</p><p><strong>This sounds convenient. It is, until it isn&#39;t.</strong></p><h3>The Honest Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPU-cfJiEXnbIaf3KR4P3Q.png" /></figure><p><strong>The recommendation:</strong> Use eager loading in production APIs. Lazy loading is a foot-gun in API contexts because it hides database calls inside serialization, loops, and service layers where you can&#39;t easily see them.</p><h3>Why EF Core Is the Best Choice (When Used Correctly)</h3><p>Here&#39;s why EF Core earns its place in serious .NET projects:</p><p><strong>1. You write less code.</strong> No manually writing INSERT, UPDATE, DELETE, and SELECT for every entity. EF Core generates that for you, and it&#39;s rarely wrong.</p><p><strong>2. Migrations are version-controlled schema changes.</strong> Instead of running SQL scripts manually across environments, you run dotnet ef migrations add and dotnet ef database update. The schema change is tracked in code alongside your application.</p><p><strong>3. LINQ is type-safe.</strong> When you rename a property in C#, your query breaks at compile time — not at runtime in production. Raw SQL strings don&#39;t give you this.</p><p><strong>4. It works with multiple databases.</strong> Swap UseSqlServer for UseNpgsql or UseSqlite and EF Core handles the dialect differences. Useful for testing with an in-memory or SQLite database.</p><p><strong>5. Change tracking is built in.</strong> EF Core watches your entities. When you load an object, modify a property, and call SaveChangesAsync(), it figures out exactly which columns changed and generates a minimal UPDATE statement.</p><p><strong>6. It integrates perfectly with .NET 8 DI and async patterns.</strong> DbContext is scoped by default, async methods are first-class, and it plays nicely with everything else in the ASP.NET Core ecosystem.</p><h3>When You Should Avoid EF Core (Or Use It Carefully)</h3><p>EF Core is not always the right tool. Be honest with yourself in these scenarios:</p><p><strong>1. High-performance bulk operations.</strong> If you need to insert 100,000 rows, context.AddRange() followed by SaveChangesAsync() is going to be slow. Use SqlBulkCopy or a library like EFCore.BulkExtensions for this.</p><p><strong>2. Complex reporting queries.</strong> When you have a multi-table aggregation query with CTEs, window functions, and conditional grouping — write it in raw SQL. EF Core&#39;s LINQ translator is good, but it&#39;s not a SQL expert. Use FromSqlRaw() or Dapper for this.</p><p><strong>3. Stored procedure-heavy databases.</strong> If your DBA owns the schema and everything goes through stored procedures, EF Core adds complexity without much benefit. Dapper is a better fit.</p><p><strong>4. When your team doesn&#39;t know what queries EF Core generates.</strong> EF Core&#39;s abstraction is only safe if you understand what&#39;s happening underneath. Always enable SQL logging in development:</p><pre>options.UseSqlServer(connectionString)<br>       .LogTo(Console.WriteLine, LogLevel.Information)<br>       .EnableSensitiveDataLogging();</pre><p>If you can&#39;t read the generated SQL, you can&#39;t trust it in production.</p><h3>The N+1 Query Problem — What It Is and How to Fix It</h3><p>This is the single most common performance disaster in EF Core applications. Understanding it will save you from some very uncomfortable production incidents.</p><h3>What Is the N+1 Problem?</h3><p>Imagine you load 100 posts. Then, in a loop, you access each post&#39;s author. EF Core fires one query to load the posts, then <strong>100 more queries</strong> — one per post — to load each author. That&#39;s 1 + 100 = 101 queries. For 1,000 posts, it&#39;s 1,001 queries.</p><p>Here&#39;s the classic setup:</p><pre>// This looks innocent<br>var posts = await _context.Posts.ToListAsync(); // 1 query<br><br>foreach (var post in posts)<br>{<br>    Console.WriteLine(post.Author.Name); // 1 query per post — N+1!<br>}</pre><p>If lazy loading is enabled, this code silently fires N additional queries. If it’s not enabled, post.Author will be null and you&#39;ll get a NullReferenceException — which, honestly, is a better outcome because at least you&#39;ll notice immediately.</p><h3>How to Fix It</h3><p><strong>Fix 1: Use Include() — the standard solution</strong></p><pre>var posts = await _context.Posts<br>    .Include(p =&gt; p.Author)<br>    .ToListAsync(); // Single query with JOIN<br><br>foreach (var post in posts)<br>{<br>    Console.WriteLine(post.Author.Name); // No extra queries<br>}</pre><p><strong>Fix 2: Use Select() to project only what you need</strong></p><p>Even better than Include in many cases — you’re not loading full entity graphs, just the columns you need:</p><pre>var postData = await _context.Posts<br>    .Select(p =&gt; new<br>    {<br>        p.Title,<br>        AuthorName = p.Author.Name<br>    })<br>    .ToListAsync();</pre><p>This generates a single, lean SQL query and doesn’t load data you’re not going to use.</p><p><strong>Fix 3: Use Split Queries for large Include chains</strong></p><p>When you’re including multiple collections, EF Core’s default is to generate one big JOIN, which can produce a cartesian explosion (thousands of duplicate rows). Use AsSplitQuery():</p><pre>var authors = await _context.Authors<br>    .Include(a =&gt; a.Posts)<br>        .ThenInclude(p =&gt; p.Comments)<br>    .AsSplitQuery() // Runs separate queries per collection instead of one massive JOIN<br>    .ToListAsync();</pre><p><strong>Fix 4: Detect N+1 in development with logging</strong></p><p>Enable EF Core logging in appsettings.Development.json:</p><pre>{<br>  &quot;Logging&quot;: {<br>    &quot;LogLevel&quot;: {<br>      &quot;Microsoft.EntityFrameworkCore.Database.Command&quot;: &quot;Information&quot;<br>    }<br>  }<br>}</pre><p>Or use a tool like <strong>MiniProfiler</strong> or <strong>EF Core Power Tools</strong> to catch unexpected queries before they reach production.</p><h3>Quick Reference — N+1 Checklist</h3><ul><li>✅ Always use Include() when you know you&#39;ll access navigation properties</li><li>✅ Prefer Select() projections for read-only API responses</li><li>✅ Use AsSplitQuery() when including multiple collections</li><li>✅ Disable lazy loading in production APIs</li><li>✅ Log generated SQL in development and review it</li><li>❌ Never loop over entities and access navigation properties without eager loading</li></ul><h3>Putting It All Together — A Clean Controller</h3><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class PostsController : ControllerBase<br>{<br>    private readonly IPostRepository _repository;<br>    public PostsController(IPostRepository repository)<br>    {<br>        _repository = repository;<br>    }<br>    [HttpGet]<br>    public async Task&lt;IActionResult&gt; GetAll([FromQuery] int page = 1, [FromQuery] int pageSize = 10)<br>    {<br>        var posts = await _repository.GetAllAsync();<br>        return Ok(posts);<br>    }<br>    [HttpGet(&quot;{id}&quot;)]<br>    public async Task&lt;IActionResult&gt; GetById(int id)<br>    {<br>        var post = await _repository.GetByIdAsync(id);<br>        return post is null ? NotFound() : Ok(post);<br>    }<br>    [HttpPost]<br>    public async Task&lt;IActionResult&gt; Create([FromBody] Post post)<br>    {<br>        var created = await _repository.CreateAsync(post);<br>        return CreatedAtAction(nameof(GetById), new { id = created.Id }, created);<br>    }<br>    [HttpPut(&quot;{id}&quot;)]<br>    public async Task&lt;IActionResult&gt; Update(int id, [FromBody] Post post)<br>    {<br>        if (id != post.Id) return BadRequest();<br>        await _repository.UpdateAsync(post);<br>        return NoContent();<br>    }<br>    [HttpDelete(&quot;{id}&quot;)]<br>    public async Task&lt;IActionResult&gt; Delete(int id)<br>    {<br>        await _repository.DeleteAsync(id);<br>        return NoContent();<br>    }<br>}</pre><h3>Final Thoughts</h3><p>Entity Framework Core is a genuinely excellent ORM. It speeds up development, keeps your schema in sync with your code, and integrates beautifully with the .NET 8 ecosystem. But it rewards developers who understand what it’s doing — and it punishes those who treat it as a black box.</p><p>The rules are actually simple:</p><ul><li>Use eager loading. Always be explicit about what you’re loading.</li><li>Project with Select() when you only need a subset of data.</li><li>Log your SQL in development. Read it. Understand it.</li><li>Don’t use lazy loading in production Web APIs.</li><li>Reach for raw SQL or Dapper when EF Core is the wrong tool for the job.</li></ul><p>Follow those rules and EF Core will be one of the most productive tools in your stack. Ignore them and you’ll spend days wondering why your API got slow when nobody changed anything.</p><p><em>Thanks for reading. If this helped you, consider sharing it with your team — especially the part about N+1 queries. It’s saved a lot of production databases.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4d52c05db29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decorator Pattern: The Secret Weapon of .NET 8 Architecture]]></title>
            <link>https://medium.com/@chandrashekharsingh25/decorator-pattern-the-secret-weapon-of-net-8-architecture-642c9866869a?source=rss-796c5dd99155------2</link>
            <guid isPermaLink="false">https://medium.com/p/642c9866869a</guid>
            <category><![CDATA[decorator-design-pattern]]></category>
            <dc:creator><![CDATA[Chandrashekhar Singh]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 05:28:01 GMT</pubDate>
            <atom:updated>2026-04-20T05:28:01.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GtBFomruASghh0o_pfFteQ.png" /></figure><p>How to build a production-grade Payment Processing System with Logging, Fraud Detection, Retry, and Audit — all without touching a single existing class.</p><p><strong>Picture this:</strong> your payment gateway is live in production. Everything is working fine. Then a new requirement lands on your desk — <strong>add fraud detection, compliance audit logging, and automatic retry on network failures.</strong></p><p>Most engineers make the same mistake here. <strong>They crack open </strong><strong>PaymentService.cs and start stuffing if-else blocks directly inside. A 200-line method balloons into 800 lines. Unit testing becomes impossible. Every new feature ships a new bug as a free gift</strong>.</p><blockquote><em>“</em>Decorator pattern is a structural design pattern that allows us to dynamically add new behavior to an object without modifying its existing code. It follows the Open/Closed Principle.<em>”</em></blockquote><p>This is precisely the problem the <strong>Decorator Pattern</strong> was designed to solve. It is a structural design pattern that lets you extend the functionality of any existing class — without changing a single line of it. Paired with .NET 8’s powerful DI system, this pattern becomes so expressive that your code starts to describe itself.</p><h3>01 — What Is the Real Problem?</h3><p>A Payment Processing System typically needs to handle these concerns simultaneously:</p><ul><li><strong>Core Logic:</strong> Actually processing the payment — the API call, database save</li><li><strong>Fraud Detection:</strong> Catching suspicious transactions before they go through</li><li><strong>Retry Mechanism:</strong> Automatically retrying on transient network failures</li><li><strong>Audit Logging:</strong> Keeping a complete record of every transaction for compliance</li><li><strong>Authorization:</strong> Ensuring only the right users can trigger payments</li></ul><p>These are all <strong>cross-cutting concerns</strong> — they are not directly part of the payment logic itself, but they must execute alongside every payment request. Dumping all of this into a single service class is a violation of the <strong>Single Responsibility Principle</strong>.</p><blockquote><em>🔥 </em><strong><em>Real Use Case:</em></strong><em> A fintech company’s payment gateway processing thousands of transactions per second. Every transaction needs a fraud check, retry on failure, a full audit trail, and authorization verification — all independent, all composable, all replaceable without breaking anything else.</em></blockquote><h3>02 — Architecture Overview</h3><p>Here is the decorator chain we are building. The request flows top to bottom, the response returns bottom to top:</p><pre>HTTP Request → PaymentController<br>        ↓<br>AuthorizationPaymentDecorator   [JWT + Role check]<br>        ↓<br>FraudDetectionDecorator         [Calculate risk score]<br>        ↓<br>RetryPaymentDecorator           [3 retries + exponential backoff]<br>        ↓<br>AuditLoggingDecorator           [Log every call, always]<br>        ↓<br>PaymentService (Core)           [The actual payment processing]</pre><p>Each layer is a separate class. Each class does exactly one thing. The controller at the top has no idea any of this complexity exists beneath it.</p><h3>03 — Step-by-Step .NET 8 Implementation</h3><h3>Step 1 — Models and Interface</h3><pre>// Models/PaymentModels.cs<br>public record PaymentRequest(<br>    string OrderId,<br>    string CustomerId,<br>    decimal Amount,<br>    string Currency,<br>    string CardToken,<br>    string IpAddress<br>);<br>public record PaymentResult(<br>    bool IsSuccess,<br>    string TransactionId,<br>    string Message,<br>    decimal Amount,<br>    DateTime ProcessedAt<br>);<br>// The core contract - the entire decorator chain is built on this<br>public interface IPaymentService<br>{<br>    Task&lt;PaymentResult&gt; ProcessPaymentAsync(<br>        PaymentRequest request,<br>        CancellationToken ct = default<br>    );<br>}</pre><h3>Step 2 — Core Payment Service (The Real Worker)</h3><pre>// Services/PaymentService.cs<br>public class PaymentService : IPaymentService<br>{<br>    private readonly IPaymentGatewayClient _gateway;<br>    private readonly IPaymentRepository _repo;<br>    public PaymentService(<br>        IPaymentGatewayClient gateway,<br>        IPaymentRepository repo)<br>    {<br>        _gateway = gateway;<br>        _repo = repo;<br>    }<br>    public async Task&lt;PaymentResult&gt; ProcessPaymentAsync(<br>        PaymentRequest request,<br>        CancellationToken ct = default)<br>    {<br>        // Pure business logic only<br>        // No logging, no retry, no fraud check - that is not this class&#39;s job<br>        var gatewayResponse = await _gateway.ChargeAsync(<br>            request.CardToken,<br>            request.Amount,<br>            request.Currency,<br>            ct<br>        );<br>        await _repo.SaveTransactionAsync(gatewayResponse, ct);<br>        return new PaymentResult(<br>            IsSuccess: gatewayResponse.Success,<br>            TransactionId: gatewayResponse.Id,<br>            Message: gatewayResponse.Message,<br>            Amount: request.Amount,<br>            ProcessedAt: DateTime.UtcNow<br>        );<br>    }<br>}</pre><h3>Step 3 — Abstract Base Decorator</h3><p>This eliminates boilerplate. Every concrete decorator inherits from this and only overrides the method it cares about.</p><pre>// Decorators/PaymentServiceDecorator.cs<br>public abstract class PaymentServiceDecorator : IPaymentService<br>{<br>    protected readonly IPaymentService _inner;<br>    protected PaymentServiceDecorator(IPaymentService inner)<br>        =&gt; _inner = inner;<br>    // Default pass-through - override only what you need<br>    public virtual Task&lt;PaymentResult&gt; ProcessPaymentAsync(<br>        PaymentRequest request,<br>        CancellationToken ct = default)<br>        =&gt; _inner.ProcessPaymentAsync(request, ct);<br>}</pre><h3>Step 4 — Fraud Detection Decorator</h3><pre>// Decorators/FraudDetectionDecorator.cs<br>public class FraudDetectionDecorator : PaymentServiceDecorator<br>{<br>    private readonly IFraudDetectionService _fraud;<br>    private readonly ILogger&lt;FraudDetectionDecorator&gt; _logger;<br>    private const decimal HighRiskThreshold = 0.85m;<br>    private const decimal LargeAmountLimit  = 50_000m;<br>    public FraudDetectionDecorator(<br>        IPaymentService inner,<br>        IFraudDetectionService fraud,<br>        ILogger&lt;FraudDetectionDecorator&gt; logger)<br>        : base(inner)<br>    {<br>        _fraud  = fraud;<br>        _logger = logger;<br>    }<br>    public override async Task&lt;PaymentResult&gt; ProcessPaymentAsync(<br>        PaymentRequest request,<br>        CancellationToken ct = default)<br>    {<br>        // Run risk scoring - ML model or rules-based engine<br>        var riskScore = await _fraud.CalculateRiskScoreAsync(request);<br>        _logger.LogInformation(<br>            &quot;Fraud check - OrderId: {OrderId}, Risk: {Risk:F2}, Amount: {Amount}&quot;,<br>            request.OrderId, riskScore, request.Amount);<br>        // High-risk: block immediately, do not proceed<br>        if (riskScore &gt; HighRiskThreshold)<br>        {<br>            _logger.LogWarning(<br>                &quot;HIGH RISK BLOCKED - OrderId: {OrderId}, Score: {Risk}&quot;,<br>                request.OrderId, riskScore);<br>            return new PaymentResult(<br>                IsSuccess: false,<br>                TransactionId: Guid.NewGuid().ToString(),<br>                Message: &quot;Transaction declined: security check failed&quot;,<br>                Amount: request.Amount,<br>                ProcessedAt: DateTime.UtcNow<br>            );<br>        }<br>        // Large amounts get flagged - but still proceed<br>        if (request.Amount &gt; LargeAmountLimit)<br>            _logger.LogWarning(<br>                &quot;Large amount transaction: {Amount} by customer {CustomerId}&quot;,<br>                request.Amount, request.CustomerId);<br>        return await _inner.ProcessPaymentAsync(request, ct);<br>    }<br>}</pre><h3>Step 5 — Retry Decorator with Exponential Backoff</h3><pre>// Decorators/RetryPaymentDecorator.cs<br>public class RetryPaymentDecorator : PaymentServiceDecorator<br>{<br>    private readonly ILogger&lt;RetryPaymentDecorator&gt; _logger;<br>    private const int MaxRetries = 3;<br>    private const int BaseDelayMs = 200;<br>    public RetryPaymentDecorator(<br>        IPaymentService inner,<br>        ILogger&lt;RetryPaymentDecorator&gt; logger)<br>        : base(inner) =&gt; _logger = logger;<br>    public override async Task&lt;PaymentResult&gt; ProcessPaymentAsync(<br>        PaymentRequest request,<br>        CancellationToken ct = default)<br>    {<br>        var attempt = 0;<br>        while (true)<br>        {<br>            try<br>            {<br>                attempt++;<br>                return await _inner.ProcessPaymentAsync(request, ct);<br>            }<br>            catch (HttpRequestException ex)<br>                when (attempt &lt; MaxRetries &amp;&amp; IsTransientError(ex))<br>            {<br>                // Exponential backoff: 200ms → 400ms → 800ms<br>                var delay = BaseDelayMs * (int)Math.Pow(2, attempt - 1);<br>                _logger.LogWarning(<br>                    &quot;Attempt {Attempt}/{Max} failed. Retrying in {Delay}ms. Error: {Msg}&quot;,<br>                    attempt, MaxRetries, delay, ex.Message);<br>                await Task.Delay(delay, ct);<br>            }<br>            catch (Exception ex) when (attempt &gt;= MaxRetries)<br>            {<br>                _logger.LogError(ex,<br>                    &quot;All {Max} payment attempts exhausted for Order: {OrderId}&quot;,<br>                    MaxRetries, request.OrderId);<br>                throw;<br>            }<br>        }<br>    }<br>    private static bool IsTransientError(HttpRequestException ex)<br>        =&gt; ex.StatusCode is<br>            HttpStatusCode.ServiceUnavailable or<br>            HttpStatusCode.GatewayTimeout    or<br>            HttpStatusCode.TooManyRequests;<br>}</pre><h3>Step 6 — Audit Logging Decorator</h3><pre>// Decorators/AuditLoggingDecorator.cs<br>public class AuditLoggingDecorator : PaymentServiceDecorator<br>{<br>    private readonly IAuditRepository _audit;<br>    private readonly ILogger&lt;AuditLoggingDecorator&gt; _logger;<br>    public AuditLoggingDecorator(<br>        IPaymentService inner,<br>        IAuditRepository audit,<br>        ILogger&lt;AuditLoggingDecorator&gt; logger)<br>        : base(inner)<br>    {<br>        _audit  = audit;<br>        _logger = logger;<br>    }<br>    public override async Task&lt;PaymentResult&gt; ProcessPaymentAsync(<br>        PaymentRequest request,<br>        CancellationToken ct = default)<br>    {<br>        var sw     = Stopwatch.StartNew();<br>        Exception?     error  = null;<br>        PaymentResult? result = null;<br>        try<br>        {<br>            result = await _inner.ProcessPaymentAsync(request, ct);<br>            return result;<br>        }<br>        catch (Exception ex)<br>        {<br>            error = ex;<br>            throw;<br>        }<br>        finally<br>        {<br>            sw.Stop();<br>            // Compliance: log every transaction - success OR failure, no exceptions<br>            await _audit.SaveAuditRecordAsync(new AuditRecord<br>            {<br>                Timestamp     = DateTime.UtcNow,<br>                OrderId       = request.OrderId,<br>                CustomerId    = request.CustomerId,<br>                Amount        = request.Amount,<br>                Currency      = request.Currency,<br>                IsSuccess     = result?.IsSuccess,<br>                TransactionId = result?.TransactionId,<br>                ErrorMessage  = error?.Message,<br>                DurationMs    = sw.ElapsedMilliseconds,<br>                IpAddress     = request.IpAddress<br>            });<br>        }<br>    }<br>}</pre><h3>Step 7 — Authorization Decorator</h3><pre>// Decorators/AuthorizationPaymentDecorator.cs<br>public class AuthorizationPaymentDecorator : PaymentServiceDecorator<br>{<br>    private readonly IHttpContextAccessor _http;<br>    public AuthorizationPaymentDecorator(<br>        IPaymentService inner,<br>        IHttpContextAccessor http)<br>        : base(inner) =&gt; _http = http;<br>    public override async Task&lt;PaymentResult&gt; ProcessPaymentAsync(<br>        PaymentRequest request,<br>        CancellationToken ct = default)<br>    {<br>        var user = _http.HttpContext?.User;<br>        if (user is null || !user.Identity?.IsAuthenticated == true)<br>            throw new UnauthorizedAccessException(&quot;Authentication required&quot;);<br>        if (!user.IsInRole(&quot;Customer&quot;) &amp;&amp; !user.IsInRole(&quot;Admin&quot;))<br>            throw new UnauthorizedAccessException(&quot;Insufficient permissions&quot;);<br>        // Customers can only pay for their own orders<br>        var userId = user.FindFirst(ClaimTypes.NameIdentifier)?.Value;<br>        if (userId != request.CustomerId &amp;&amp; !user.IsInRole(&quot;Admin&quot;))<br>            throw new UnauthorizedAccessException(<br>                &quot;Cannot process payment on behalf of another customer&quot;);<br>        return await _inner.ProcessPaymentAsync(request, ct);<br>    }<br>}</pre><h3>Step 8 — Register Everything with Scrutor</h3><p>Before we write a single line, let’s address the obvious question: <strong>why do we need Scrutor at all?</strong></p><p>.NET’s built-in DI container does not natively support the Decorator Pattern. If you try to register decorators without any helper library, you end up writing this manually:</p><pre>// ❌ Without Scrutor — ugly, fragile, and painful to maintain<br>builder.Services.AddScoped&lt;IPaymentService&gt;(provider =&gt;<br>{<br>    // You have to manually construct the entire chain yourself<br>    var core = new PaymentService(<br>        provider.GetRequiredService&lt;IPaymentGatewayClient&gt;(),<br>        provider.GetRequiredService&lt;IPaymentRepository&gt;()<br>    );<br>    var withAudit = new AuditLoggingDecorator(<br>        core,<br>        provider.GetRequiredService&lt;IAuditRepository&gt;(),<br>        provider.GetRequiredService&lt;ILogger&lt;AuditLoggingDecorator&gt;&gt;()<br>    );<br>    var withRetry = new RetryPaymentDecorator(<br>        withAudit,<br>        provider.GetRequiredService&lt;ILogger&lt;RetryPaymentDecorator&gt;&gt;()<br>    );<br>    var withFraud = new FraudDetectionDecorator(<br>        withRetry,<br>        provider.GetRequiredService&lt;IFraudDetectionService&gt;(),<br>        provider.GetRequiredService&lt;ILogger&lt;FraudDetectionDecorator&gt;&gt;()<br>    );<br>    return new AuthorizationPaymentDecorator(<br>        withFraud,<br>        provider.GetRequiredService&lt;IHttpContextAccessor&gt;()<br>    );<br>});</pre><p>This is brittle. Every time you add, remove, or reorder a decorator, you have to rewrite this entire factory block. Constructor changes in any decorator break it silently at runtime. It also completely defeats the elegance of the pattern.</p><p><strong>Scrutor solves this.</strong> It is a small NuGet package that adds a Decorate&lt;TService, TDecorator&gt;() extension method to the .NET service collection. It internally performs the same manual wiring shown above — but you never have to see or touch it. Each decorator is resolved through the DI container normally, with all its own dependencies injected automatically.</p><p>First, install Scrutor:</p><pre>dotnet add package Scrutor</pre><p>Now the same registration becomes clean and readable:</p><p>Then wire it all up in Program.cs:</p><pre>// ✅ With Scrutor - one line per decorator, order is explicit and obvious<br>// Program.cs<br>var builder = WebApplication.CreateBuilder(args);<br>builder.Services.AddHttpContextAccessor();<br>builder.Services.AddMemoryCache();<br>// Step 1: Register the core service<br>builder.Services.AddScoped&lt;IPaymentService, PaymentService&gt;();<br>// Step 2: Layer on the decorators<br>// ⚠️ IMPORTANT: last registered = outermost = first to execute<br>// Final execution order: Authorization → Fraud → Retry → AuditLogging → Core<br>builder.Services.Decorate&lt;IPaymentService, AuditLoggingDecorator&gt;();<br>builder.Services.Decorate&lt;IPaymentService, RetryPaymentDecorator&gt;();<br>builder.Services.Decorate&lt;IPaymentService, FraudDetectionDecorator&gt;();<br>builder.Services.Decorate&lt;IPaymentService, AuthorizationPaymentDecorator&gt;();<br>builder.Services.AddControllers();<br>var app = builder.Build();<br>app.UseAuthentication();<br>app.UseAuthorization();<br>app.MapControllers();<br>app.Run();</pre><p>There is one critical gotcha here that trips up almost everyone the first time: <strong>the registration order is reversed.</strong></p><p>Each call to Decorate() wraps the currently registered IPaymentService with a new outer layer. So the last decorator you register becomes the outermost wrapper — the first one to execute when a request comes in.</p><p>Think of it like putting on layers of clothing. The last thing you put on is the first thing people see. In our case:</p><pre>Registration order (bottom-up):        Execution order (top-down):<br>━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━         ━━━━━━━━━━━━━━━━━━━━━━━━━━━<br>1. PaymentService (core)               1. AuthorizationPaymentDecorator  ← checks JWT first<br>2. Decorate → AuditLoggingDecorator    2. FraudDetectionDecorator        ← then fraud score<br>3. Decorate → RetryPaymentDecorator    3. RetryPaymentDecorator          ← then retry logic<br>4. Decorate → FraudDetectionDecorator  4. AuditLoggingDecorator          ← then audit log<br>5. Decorate → AuthorizationDecorator   5. PaymentService (core)          ← finally, the work</pre><p>Get this order wrong — say, register Authorization before AuditLogging — and your fraud check runs before you have even verified the user is authenticated. In a payment system, that is not just a code smell, it is a security hole.</p><p>The rule is simple: <strong>register the decorator you want to execute last, first. Register the decorator you want to execute first, last.</strong></p><h3>Step 9 — The Controller (Clean and Unaware of All of the Above)</h3><pre>// Controllers/PaymentController.cs<br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>[Authorize]<br>public class PaymentController : ControllerBase<br>{<br>    private readonly IPaymentService _paymentService;<br>    public PaymentController(IPaymentService paymentService)<br>        =&gt; _paymentService = paymentService;<br>    // DI automatically injects the fully-decorated service<br>    [HttpPost]<br>    public async Task&lt;IActionResult&gt; ProcessPayment(<br>        [FromBody] PaymentRequest request,<br>        CancellationToken ct)<br>    {<br>        try<br>        {<br>            var result = await _paymentService.ProcessPaymentAsync(request, ct);<br>            return result.IsSuccess ? Ok(result) : BadRequest(result);<br>        }<br>        catch (UnauthorizedAccessException ex)<br>            { return Unauthorized(new { ex.Message }); }<br>        catch (ArgumentException ex)<br>            { return BadRequest(new { ex.Message }); }<br>    }<br>}</pre><blockquote><em>The controller has no idea fraud detection or retry logic even exists. It simply sends a request and receives a result. All the complexity lives in the decorator chain — and that is exactly the point.</em></blockquote><h3>04 — What Do You Actually Gain?</h3><p><strong>Single Responsibility.</strong> Every class does exactly one thing. The fraud detector knows nothing about retry. The audit logger knows nothing about authorization. Each is a clean, focused unit.</p><p><strong>Open / Closed Principle.</strong> Need a new feature? Write a new decorator, add one line to Program.cs. The core service is never opened, never risked, never broken.</p><p><strong>True Testability.</strong> Each decorator is independently unit-testable. Mock the inner service, test just the decorator’s behavior in isolation. No 800-line test setup required.</p><p><strong>Runtime Composability.</strong> Different combinations for different environments. Development gets logging only. Production gets the full stack. Zero code changes — just DI configuration.</p><p><strong>Reusability Across Services.</strong> The RetryDecorator you built for payments works equally well on your email service, notification service, or any other external call. Write once, compose everywhere.</p><p><strong>Self-Documenting Architecture.</strong> Reading Program.cs tells you exactly what the system does. The decorator chain is living documentation that never goes stale.</p><h3>05 — When to Use It. When to Skip It.</h3><p><strong>Use the Decorator Pattern when:</strong></p><ul><li>You have cross-cutting concerns — logging, caching, validation, retry, authorization</li><li>You cannot modify the existing class (sealed, third-party library)</li><li>You need to change behavior dynamically at runtime</li><li>Different feature combinations are needed for different environments</li><li>Unit testing matters and you want each concern isolated and testable independently</li></ul><p><strong>Skip it when:</strong></p><ul><li>You only need to add one simple behavior — straight inheritance is cleaner</li><li>Your team is unfamiliar with the pattern — onboarding cost will outweigh gains short-term</li><li>Your decorator chain would exceed 5–6 layers — debugging becomes a maze</li><li>Decorators need to share state with each other — this pattern assumes each layer is independent</li><li>It is a simple CRUD app with no real cross-cutting concerns to separate</li></ul><h3>06 — Why This Pattern Actually Matters</h3><p>In real production systems, code is written once but <em>maintained thousands of times.</em> When audit requirements change due to new regulations, when a new fraud model needs to be swapped in, when retry logic needs fine-tuning after an outage — with the Decorator Pattern, every one of those changes is a single file, a single class, a single pull request.</p><p>Without it? Your PaymentService.cs becomes an 800-line monster doing twelve things at once. Nobody wants to touch it. Every change comes with a prayer and a three-hour regression test. New engineers are afraid to break it. Veterans have already stopped caring about its quality.</p><blockquote><em>“</em>Good architecture is not about adding features faster today. It is about maintaining the same speed six months from now.<em>”</em></blockquote><p>The Decorator Pattern makes your system <strong>horizontally scalable for behavior</strong>. Just as microservices horizontally scale infrastructure concerns, decorators do the same at the application layer — each behavior is independent, swappable, and testable on its own.</p><p>With .NET 8’s DI system and Scrutor’s Decorate() extension, this pattern requires almost no ceremony. Add one line — gain one layer. Remove one line — the layer disappears. No other code in the system notices. That is the kind of confidence that separates maintainable codebases from legacy nightmares.</p><h3>TL;DR — Quick Summary</h3><ul><li><strong>Decorator Pattern</strong> extends existing objects without modifying them — wrapping is the mechanism</li><li>In a payment system: Authorization → Fraud → Retry → Audit → Core, each in its own isolated class</li><li><strong>Scrutor’s</strong> Decorate() makes .NET 8 DI registration a single line per decorator</li><li>Registration order is reversed — last registered = outermost = first to execute. Get this wrong and your auth check runs after fraud detection</li><li>Every decorator is independently unit-testable, reusable across services, and replaceable without touching anything else</li><li>Use it for cross-cutting concerns. Skip it when chains go deep or the team is not yet familiar with the pattern</li><li>The real payoff is not day one — it is month six, when a new requirement arrives and your team ships it in an afternoon</li></ul><p>The full source code is available here: <a href="https://github.com/CSSinghNet/DecoratorPattern">https://github.com/CSSinghNet/DecoratorPattern</a></p><p><strong><em>Tags:</em></strong><em> .NET 8, C#, Design Patterns, Decorator Pattern, Web API, Clean Architecture, SOLID Principles, Payment Systems, Scrutor</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=642c9866869a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles in .NET 8 C#: A Complete Guide to Building Clean and Scalable Web APIs]]></title>
            <link>https://medium.com/@chandrashekharsingh25/solid-principles-in-net-8-c-a-complete-guide-to-building-clean-and-scalable-web-apis-559a394291cc?source=rss-796c5dd99155------2</link>
            <guid isPermaLink="false">https://medium.com/p/559a394291cc</guid>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Chandrashekhar Singh]]></dc:creator>
            <pubDate>Thu, 16 Apr 2026 03:19:02 GMT</pubDate>
            <atom:updated>2026-04-16T03:19:02.959Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Stop writing code that makes future-you cry at 2 AM.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2KxBlAB6vIoOK2HuXL_nQA.png" /></figure><p>Every developer has inherited a codebase that feels like a ticking time bomb. You touch one thing and three other things break. You add a feature and suddenly need to rewrite half the project. You read a method that does twelve different things and has no clear purpose.</p><p><strong>SOLID principles exist to prevent exactly that.</strong> They are not theoretical buzzwords. They are <strong>practical </strong>rules that, once applied, make your Web API in .NET 8 easier to extend, test, debug, and hand off to other developers.</p><p>Let’s go through all <strong>five </strong>principles — one by one — with real examples from the world of building Web APIs: think order management, user authentication, notification systems, invoice generation. Things you actually build at work.</p><h3>S — Single Responsibility Principle</h3><blockquote><strong>“A class should have only one reason to change, meaning it should have only one responsibility or job.”</strong></blockquote><p>This is the most violated principle in enterprise codebases. The symptom is a class called <strong>OrderService </strong>that handles business logic, sends emails, writes logs, formats responses, talks to the database, and probably also does your taxes.</p><h3>The Problem</h3><pre>public class OrderService<br>{<br>    public void PlaceOrder(Order order)<br>    {<br>        // Validate order<br>        if (order.Items.Count == 0)<br>            throw new Exception(&quot;Order must have items&quot;);<br>        // Save to database<br>        using var conn = new SqlConnection(&quot;...&quot;);<br>        conn.Execute(&quot;INSERT INTO Orders ...&quot;, order);<br>        // Send confirmation email<br>        var smtpClient = new SmtpClient(&quot;smtp.company.com&quot;);<br>        smtpClient.Send(new MailMessage(&quot;no-reply@company.com&quot;, order.CustomerEmail,<br>            &quot;Order Confirmed&quot;, $&quot;Your order #{order.Id} is placed.&quot;));<br>        // Write log<br>        File.AppendAllText(&quot;orders.log&quot;, $&quot;{DateTime.Now}: Order {order.Id} placed\n&quot;);<br>    }<br>}</pre><p>This class has four reasons to change: validation rules change, database schema changes, email template changes, or logging strategy changes. Any one of those changes forces you into this class, risking breaking the other three.</p><h3>The Fix</h3><p>Split responsibilities cleanly:</p><pre>// Responsibility 1: Business rules only<br>public class OrderService<br>{<br>    private readonly IOrderRepository _repository;<br>    private readonly INotificationService _notificationService;<br>    public OrderService(IOrderRepository repository, INotificationService notificationService)<br>    {<br>        _repository = repository;<br>        _notificationService = notificationService;<br>    }<br>    public async Task PlaceOrderAsync(Order order)<br>    {<br>        if (order.Items.Count == 0)<br>            throw new InvalidOperationException(&quot;Order must have at least one item.&quot;);<br>        await _repository.SaveAsync(order);<br>        await _notificationService.SendOrderConfirmationAsync(order);<br>    }<br>}<br><br>// Responsibility 2: Data access only<br>public class OrderRepository : IOrderRepository<br>{<br>    private readonly AppDbContext _context;<br>    public OrderRepository(AppDbContext context) =&gt; _context = context;<br>    public async Task SaveAsync(Order order)<br>    {<br>        _context.Orders.Add(order);<br>        await _context.SaveChangesAsync();<br>    }<br>}<br>// Responsibility 3: Notifications only<br>public class EmailNotificationService : INotificationService<br>{<br>    public async Task SendOrderConfirmationAsync(Order order)<br>    {<br>        // Send email logic here<br>    }<br>}</pre><p>Now each class has exactly one job. If the email template changes, you only touch <strong>EmailNotificationService</strong>. If the database schema changes, you only touch <strong>OrderRepository</strong>. The API controller calling <strong>OrderService </strong>never needs to know any of this happened.</p><h3>O — Open/Closed Principle</h3><blockquote><strong>“Software entities should be open for extension but closed for modification.”</strong></blockquote><p>Your existing, tested code should not need to be rewritten every time a new business requirement comes in. You extend behavior by adding new code, not by cracking open old code.</p><h3>The Problem</h3><p>Imagine your API needs to calculate discounts. You write this:</p><pre>public class DiscountService<br>{<br>    public decimal Calculate(Order order, string customerType)<br>    {<br>        if (customerType == &quot;Premium&quot;)<br>            return order.Total * 0.20m;<br>        else if (customerType == &quot;Seasonal&quot;)<br>            return order.Total * 0.10m;<br>        else<br>            return 0;<br>    }<br>}</pre><p>A new customer type arrives next sprint. You open this file, add another <strong>else if</strong>, and hope nothing breaks. Next sprint, another customer type. This never ends, and every change to this method puts the existing discount logic at risk.</p><h3>The Fix</h3><p>Define an abstraction. Each discount rule becomes its own class.</p><pre>public interface IDiscountStrategy<br>{<br>    bool AppliesTo(Customer customer);<br>    decimal Calculate(decimal orderTotal);<br>}<br><br>public class PremiumDiscount : IDiscountStrategy<br>{<br>    public bool AppliesTo(Customer customer) =&gt; customer.Type == CustomerType.Premium;<br>    public decimal Calculate(decimal orderTotal) =&gt; orderTotal * 0.20m;<br>}<br>public class SeasonalDiscount : IDiscountStrategy<br>{<br>    public bool AppliesTo(Customer customer) =&gt; customer.IsSeasonalMember;<br>    public decimal Calculate(decimal orderTotal) =&gt; orderTotal * 0.10m;<br>}<br>public class DiscountService<br>{<br>    private readonly IEnumerable&lt;IDiscountStrategy&gt; _strategies;<br>    public DiscountService(IEnumerable&lt;IDiscountStrategy&gt; strategies)<br>    {<br>        _strategies = strategies;<br>    }<br>    public decimal Calculate(Order order, Customer customer)<br>    {<br>        var strategy = _strategies.FirstOrDefault(s =&gt; s.AppliesTo(customer));<br>        return strategy?.Calculate(order.Total) ?? 0;<br>    }<br>}</pre><p>Register all strategies in <strong>Program.cs</strong>:</p><pre>builder.Services.AddScoped&lt;IDiscountStrategy, PremiumDiscount&gt;();<br>builder.Services.AddScoped&lt;IDiscountStrategy, SeasonalDiscount&gt;();<br>builder.Services.AddScoped&lt;IDiscountService, DiscountService&gt;();</pre><p>Now when a new customer type arrives, you create a new class implementing <strong>IDiscountStrategy</strong>. The <strong>DiscountService</strong> itself never changes. It is closed for modification and open for extension.</p><h3>L — Liskov Substitution Principle</h3><blockquote><strong>“Derived classes should be substitutable for their base classes without altering the correctness of the program.”</strong></blockquote><p>This principle is often described in abstract terms, but it has a very practical meaning in API development: if you’re using interfaces or base classes, every implementation must behave in a way that callers can rely on.</p><h3>The Problem</h3><p>Your API exports reports. You have a base class:</p><pre>public abstract class ReportExporter<br>{<br>    public abstract void Export(Report report, string filePath);<br>    public abstract bool SupportsStreaming();<br>}<br><br>public class PdfExporter : ReportExporter<br>{<br>    public override void Export(Report report, string filePath)<br>    {<br>        // Exports to PDF<br>    }<br>    public override bool SupportsStreaming() =&gt; true;<br>}<br>public class CsvExporter : ReportExporter<br>{<br>    public override void Export(Report report, string filePath)<br>    {<br>        // Exports to CSV<br>    }<br>    public override bool SupportsStreaming()<br>    {<br>        throw new NotImplementedException(&quot;CSV does not support streaming&quot;);<br>    }<br>}</pre><p><strong>CsvExporter </strong>cannot fully substitute <strong>ReportExporter</strong>. Any caller invoking <strong>SupportsStreaming() </strong>is in for a runtime crash. This violates LSP.</p><h3>The Fix</h3><p>Don’t force capabilities into a base class that not all implementations share. Split the interface:</p><pre>public interface IReportExporter<br>{<br>    void Export(Report report, string filePath);<br>}<br><br>public interface IStreamingReportExporter : IReportExporter<br>{<br>    Stream ExportToStream(Report report);<br>}<br>public class PdfExporter : IStreamingReportExporter<br>{<br>    public void Export(Report report, string filePath) { /* ... */ }<br>    public Stream ExportToStream(Report report) { /* ... */ return new MemoryStream(); }<br>}<br>public class CsvExporter : IReportExporter<br>{<br>    public void Export(Report report, string filePath) { /* ... */ }<br>}</pre><p>Now callers that need streaming can depend on <strong>IStreamingReportExporter</strong>. Callers that just need to export a file depend on <strong>IReportExporter</strong>. Every implementation can substitute cleanly without throwing surprises.</p><p>In your controller:</p><pre>[HttpGet(&quot;export/{format}&quot;)]<br>public IActionResult ExportReport(string format)<br>{<br>    IReportExporter exporter = format switch<br>    {<br>        &quot;pdf&quot; =&gt; _pdfExporter,<br>        &quot;csv&quot; =&gt; _csvExporter,<br>        _ =&gt; throw new ArgumentException(&quot;Unsupported format&quot;)<br>    };<br>    exporter.Export(_report, &quot;/exports/report&quot;);<br>    return Ok();<br>}</pre><h3>I — Interface Segregation Principle</h3><blockquote><strong>“Clients should not be forced to depend on interfaces they do not use.”</strong></blockquote><p>Fat interfaces are a common mistake when developers try to be “future-proof” by putting everything into a single interface. The result is classes full of empty method bodies or <strong>throw new NotImplementedException()</strong> calls — a clear sign something is wrong.</p><h3>The Problem</h3><pre>public interface IUserService<br>{<br>    Task&lt;User&gt; GetByIdAsync(int id);<br>    Task CreateUserAsync(User user);<br>    Task UpdateUserAsync(User user);<br>    Task DeleteUserAsync(int id);<br>    Task&lt;string&gt; GeneratePasswordResetTokenAsync(int userId);<br>    Task SendWelcomeEmailAsync(int userId);<br>    Task&lt;UserActivityReport&gt; GetUserActivityReportAsync(int userId);<br>}</pre><p>A <strong>ReadOnlyUserService </strong>that only queries data now has to implement <strong>CreateUserAsync, </strong><strong>DeleteUserAsync, and </strong><strong>SendWelcomeEmailAsync </strong>— things it has nothing to do with.</p><h3>The Fix</h3><p>Segregate by capability:</p><pre>public interface IUserReader<br>{<br>    Task&lt;User&gt; GetByIdAsync(int id);<br>    Task&lt;IEnumerable&lt;User&gt;&gt; GetAllAsync();<br>}<br><br>public interface IUserWriter<br>{<br>    Task CreateAsync(User user);<br>    Task UpdateAsync(User user);<br>    Task DeleteAsync(int id);<br>}<br>public interface IUserAuthService<br>{<br>    Task&lt;string&gt; GeneratePasswordResetTokenAsync(int userId);<br>}<br><br>public interface IUserNotifier<br>{<br>    Task SendWelcomeEmailAsync(int userId);<br>}</pre><p>Now your <strong>AdminUserService </strong>implements <strong>IUserReader </strong>and <strong>IUserWriter</strong>. Your <strong>AuthenticationService </strong>implements <strong>IUserAuthService</strong>. Your <strong>EmailService </strong>implements <strong>IUserNotifier</strong>.</p><p>In your minimal API or controller, you inject only what you need:</p><pre>app.MapGet(&quot;/users/{id}&quot;, async (int id, IUserReader userReader) =&gt;<br>{<br>    var user = await userReader.GetByIdAsync(id);<br>    return user is null ? Results.NotFound() : Results.Ok(user);<br>});<br><br>app.MapPost(&quot;/users&quot;, async (User user, IUserWriter userWriter) =&gt;<br>{<br>    await userWriter.CreateAsync(user);<br>    return Results.Created($&quot;/users/{user.Id}&quot;, user);<br>});</pre><p>Each endpoint declares exactly what it depends on. Nothing more. This makes the code self-documenting and trivial to unit test.</p><h3>D — Dependency Inversion Principle</h3><blockquote><strong>“High-level modules should not depend on low-level modules. Both should depend on abstractions.”</strong></blockquote><p>This is the principle that makes .NET’s built-in dependency injection so powerful. When you inject <strong>ILogger </strong>instead of using <strong>Console.WriteLine</strong>, or inject <strong>IEmailSender</strong> instead of <strong>new SmtpClient(...)</strong>, you are practicing dependency inversion.</p><h3>The Problem</h3><pre>public class InvoiceService<br>{<br>    private readonly SqlInvoiceRepository _repository;<br>    private readonly SmtpEmailSender _emailSender;<br><br>    public InvoiceService()<br>    {<br>        _repository = new SqlInvoiceRepository(&quot;Server=prod;...&quot;);<br>        _emailSender = new SmtpEmailSender(&quot;smtp.company.com&quot;, 587);<br>    }<br>    public async Task IssueInvoiceAsync(Invoice invoice)<br>    {<br>        await _repository.SaveAsync(invoice);<br>        await _emailSender.SendAsync(invoice.CustomerEmail, &quot;Your invoice is ready&quot;, &quot;...&quot;);<br>    }<br>}</pre><p><strong>InvoiceService </strong>is chained directly to SQL Server and SMTP. You cannot unit test this. You cannot swap the email provider. You cannot use a test database. The high-level business logic is enslaved to low-level infrastructure decisions.</p><h3>The Fix</h3><p>Depend on interfaces, not concrete types. Let the DI container wire everything up.</p><pre>// Abstractions<br>public interface IInvoiceRepository<br>{<br>    Task SaveAsync(Invoice invoice);<br>    Task&lt;Invoice?&gt; GetByIdAsync(int id);<br>}<br><br>public interface IEmailSender<br>{<br>    Task SendAsync(string to, string subject, string body);<br>}<br><br>// High-level module depends on abstractions<br>public class InvoiceService<br>{<br>    private readonly IInvoiceRepository _repository;<br>    private readonly IEmailSender _emailSender;<br>    private readonly ILogger&lt;InvoiceService&gt; _logger;<br>    public InvoiceService(<br>        IInvoiceRepository repository,<br>        IEmailSender emailSender,<br>        ILogger&lt;InvoiceService&gt; logger)<br>    {<br>        _repository = repository;<br>        _emailSender = emailSender;<br>        _logger = logger;<br>    }<br>    public async Task IssueInvoiceAsync(Invoice invoice)<br>    {<br>        await _repository.SaveAsync(invoice);<br>        await _emailSender.SendAsync(<br>            invoice.CustomerEmail,<br>            $&quot;Invoice #{invoice.Id} Issued&quot;,<br>            $&quot;Total due: {invoice.TotalAmount:C}&quot;);<br>        _logger.LogInformation(&quot;Invoice {InvoiceId} issued to {Email}&quot;, invoice.Id, invoice.CustomerEmail);<br>    }<br>}<br>// Low-level implementations<br>public class SqlInvoiceRepository : IInvoiceRepository<br>{<br>    private readonly AppDbContext _context;<br>    public SqlInvoiceRepository(AppDbContext context) =&gt; _context = context;<br>    public async Task SaveAsync(Invoice invoice)<br>    {<br>        _context.Invoices.Add(invoice);<br>        await _context.SaveChangesAsync();<br>    }<br>    public async Task&lt;Invoice?&gt; GetByIdAsync(int id) =&gt;<br>        await _context.Invoices.FindAsync(id);<br>}<br>public class SmtpEmailSender : IEmailSender<br>{<br>    public async Task SendAsync(string to, string subject, string body)<br>    {<br>        // Real SMTP logic<br>    }<br>}</pre><p>Register in Program.cs:</p><pre>builder.Services.AddScoped&lt;IInvoiceRepository, SqlInvoiceRepository&gt;();<br>builder.Services.AddScoped&lt;IEmailSender, SmtpEmailSender&gt;();<br>builder.Services.AddScoped&lt;InvoiceService&gt;();</pre><p>Now in your tests, you can inject a mock <strong>IEmailSender </strong>and a mock <strong>IInvoiceRepository</strong>. No SMTP server needed. No database needed. Your business logic tests run in milliseconds.</p><pre>[Test]<br>public async Task IssueInvoice_ShouldSaveAndSendEmail()<br>{<br>    var mockRepo = Substitute.For&lt;IInvoiceRepository&gt;();<br>    var mockEmail = Substitute.For&lt;IEmailSender&gt;();<br>    var logger = Substitute.For&lt;ILogger&lt;InvoiceService&gt;&gt;();<br><br>    var service = new InvoiceService(mockRepo, mockEmail, logger);<br>    var invoice = new Invoice { Id = 1, CustomerEmail = &quot;client@example.com&quot;, TotalAmount = 500m };<br>    await service.IssueInvoiceAsync(invoice);<br>    await mockRepo.Received(1).SaveAsync(invoice);<br>    await mockEmail.Received(1).SendAsync(&quot;client@example.com&quot;, Arg.Any&lt;string&gt;(), Arg.Any&lt;string&gt;());<br>}</pre><h3>Putting It All Together in a .NET 8 Web API</h3><p>Here is a quick look at how a clean API controller looks when all five principles are applied:</p><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class OrdersController : ControllerBase<br>{<br>    private readonly IOrderService _orderService;<br><br>    public OrdersController(IOrderService orderService)<br>    {<br>        _orderService = orderService;<br>    }<br><br>    [HttpPost]<br>    public async Task&lt;IActionResult&gt; PlaceOrder([FromBody] PlaceOrderRequest request)<br>    {<br>        var result = await _orderService.PlaceOrderAsync(request);<br>        return result.IsSuccess<br>            ? CreatedAtAction(nameof(GetOrder), new { id = result.OrderId }, result)<br>            : BadRequest(result.Error);<br>    }<br><br>    [HttpGet(&quot;{id}&quot;)]<br>    public async Task&lt;IActionResult&gt; GetOrder(int id)<br>    {<br>        var order = await _orderService.GetOrderAsync(id);<br>        return order is null ? NotFound() : Ok(order);<br>    }<br>}</pre><p>The controller does exactly one thing: it maps HTTP requests to service calls. It has no knowledge of databases, email, discounts, or logging. It depends on an abstraction (<strong>IOrderService</strong>), not a concrete class. It is clean, readable, and testable in isolation.</p><h3>Why This Matters for You as a .NET Developer</h3><p>Writing SOLID code is not about following rules for the sake of rules. It is about pragmatics:</p><p><strong>You can test each unit in isolation.</strong> Because dependencies are injected via interfaces, unit tests are fast and reliable. You mock what you don’t want to test. You test what you care about.</p><p><strong>Features are safer to add.</strong> The Open/Closed Principle means new business requirements become new classes, not risky edits to existing, working code.</p><p><strong>Onboarding new developers is faster.</strong> When every class has one clear job, new developers can understand a piece of the system without needing to understand all of it.</p><p><strong>Your API survives changing infrastructure.</strong> Switching from SQL Server to PostgreSQL, from SMTP to SendGrid, from in-memory cache to Redis — these changes only touch the implementing class, not the business logic that depends on the interface.</p><p><strong>Refactoring is less terrifying.</strong> When responsibilities are separated and dependencies are inverted, you can confidently rename, move, or replace a piece of the system without unraveling everything else.</p><h3>Final Thought</h3><p>SOLID is not a checklist to complete. It is a way of thinking about how code should grow. Start small: the next time you write a service class, ask yourself if it has more than one reason to change. The next time you write a concrete dependency inside a class, ask yourself if an interface would serve better.</p><p>You don’t need to apply all five perfectly on day one. But the earlier you start, the better your codebase will age — and the fewer 2 AM incidents you’ll have debugging a method that nobody can explain.</p><p>Clean code is not written once. It is designed continuously, one good decision at a time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=559a394291cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adapter Pattern in C# .NET Web API: Amazon S3, Azure Blob, and Google Cloud Storage]]></title>
            <link>https://medium.com/@chandrashekharsingh25/adapter-pattern-in-c-net-web-api-amazon-s3-azure-blob-and-google-cloud-storage-4497d32a59e5?source=rss-796c5dd99155------2</link>
            <guid isPermaLink="false">https://medium.com/p/4497d32a59e5</guid>
            <dc:creator><![CDATA[Chandrashekhar Singh]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 09:21:51 GMT</pubDate>
            <atom:updated>2026-03-26T09:21:51.841Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>A deep dive into building a clean, scalable, production-ready cloud storage abstraction using the Adapter Pattern, Options Pattern, and .NET’s Dependency Injection — with Amazon S3, Azure Blob Storage, and Google Cloud Storage.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*msIeXKN3pu2HLX7dMH_VAQ.png" /></figure><h3>The Problem</h3><p>Imagine you’re building a .NET Web API that needs to store files in the cloud. Simple enough — until your product manager says:</p><blockquote>“<strong>We need to support Amazon S3, Azure Blob Storage, and Google Cloud Storage. Oh, and the client should be able to switch providers without a code change.</strong>”</blockquote><p>Each cloud provider has a completely different SDK:</p><ul><li><strong>Amazon S3</strong> uses AmazonS3Client from AWSSDK.S3</li><li><strong>Azure Blob Storage</strong> uses BlobServiceClient from Azure.Storage.Blobs</li><li><strong>Google Cloud Storage</strong> uses StorageClient from Google.Cloud.Storage.V1</li></ul><p>If you write your controllers directly against these SDKs, you end up with a fragile, tightly coupled mess that’s painful to test, impossible to swap, and violates almost every SOLID principle in the book.</p><p>The solution? The <strong>Adapter Pattern</strong> — combined with the <strong>Options Pattern</strong> and .NET’s <strong>Dependency Injection</strong> for a truly production-grade architecture.</p><h3>What Is the Adapter Pattern?</h3><p>The <strong>Adapter Pattern </strong>is a <strong>structural design pattern</strong> that <strong>acts as a bridge between two incompatible interfaces.</strong> Think of it like a travel adapter — your laptop charger hasn’t changed, but an adapter lets it plug into any socket worldwide.</p><p>In software terms:</p><ul><li>You define <strong>one interface</strong> that your application talks to</li><li>Each provider gets its own <strong>Adapter class</strong> that wraps the SDK and implements your interface</li><li>Your controllers and services never know which provider they’re talking to</li></ul><h3>Architecture Overview</h3><p>Here’s the full picture of what we’re building:</p><pre>FilesController<br>      |<br>      | depends on<br>      ↓<br>ICloudStorageService  (your clean interface)<br>      |<br>      |--- S3StorageAdapter      → AmazonS3Client     (AWS SDK)<br>      |--- AzureBlobAdapter      → BlobServiceClient  (Azure SDK)<br>      └--- GcsStorageAdapter     → StorageClient      (GCP SDK)<br><br>CloudStorageOptions   (Options Pattern - strongly typed config)<br>      ↑<br>appsettings.json      (Provider + per-provider credentials)<br>Program.cs            (DI registration via AddCloudStorage() extension)</pre><p>One interface. Three adapters. Zero coupling in your controllers.</p><h3>Step 1: Define the Options Classes</h3><p>The Options Pattern gives you strongly typed, validated configuration instead of raw IConfiguration strings scattered through your code.</p><pre>public class S3Options<br>{<br>    public string AccessKey { get; set; } = string.Empty;<br>    public string SecretKey { get; set; } = string.Empty;<br>    public string Region    { get; set; } = string.Empty;<br>}<br><br>public class AzureOptions<br>{<br>    public string ConnectionString { get; set; } = string.Empty;<br>}<br><br>public class GcsOptions<br>{<br>    public string ProjectId { get; set; } = string.Empty;<br>}<br><br>public class CloudStorageOptions<br>{<br>    public const string SectionName = &quot;CloudStorage&quot;;<br>    public string      Provider { get; set; } = string.Empty;<br>    public S3Options   S3       { get; set; } = new();<br>    public AzureOptions Azure   { get; set; } = new();<br>    public GcsOptions  Gcs      { get; set; } = new();<br>}</pre><p>Each provider has its own dedicated options class. CloudStorageOptions is the root that maps to your config section and holds a Provider discriminator to tell the factory which adapter to instantiate.</p><h3>Step 2: Configure appsettings.json</h3><pre>{<br>  &quot;CloudStorage&quot;: {<br>    &quot;Provider&quot;: &quot;Azure&quot;,<br>    &quot;S3&quot;: {<br>      &quot;AccessKey&quot;: &quot;your-access-key&quot;,<br>      &quot;SecretKey&quot;: &quot;your-secret-key&quot;,<br>      &quot;Region&quot;:    &quot;us-east-1&quot;<br>    },<br>    &quot;Azure&quot;: {<br>      &quot;ConnectionString&quot;: &quot;DefaultEndpointsProtocol=https;AccountName=myaccount;...&quot;<br>    },<br>    &quot;Gcs&quot;: {<br>      &quot;ProjectId&quot;: &quot;my-gcp-project-id&quot;<br>    }<br>  }<br>}</pre><p>To switch from Azure to S3, you change exactly <strong>one line</strong> — &quot;Provider&quot;: &quot;S3&quot; — and redeploy. No code changes, no recompile.</p><h3>Step 3: Define the Common Interface</h3><p>This is the heart of the pattern. All three adapters implement this single interface:</p><pre>public interface ICloudStorageService<br>{<br>    Task&lt;string&gt; UploadAsync(string container, string fileName, Stream content);<br>    Task&lt;Stream&gt; DownloadAsync(string container, string fileName);<br>    Task DeleteAsync(string container, string fileName);<br>}</pre><p>Your entire application only ever sees ICloudStorageService. The AWS SDK, Azure SDK, and GCP SDK are implementation details hidden behind this contract.</p><h3>Step 4: Build the Adapters</h3><h3>Amazon S3 Adapter</h3><pre>public class S3StorageAdapter : ICloudStorageService<br>{<br>    private readonly AmazonS3Client _client;<br>    private readonly ILogger&lt;S3StorageAdapter&gt; _logger;<br>public S3StorageAdapter(<br>        IOptions&lt;CloudStorageOptions&gt; options,<br>        ILogger&lt;S3StorageAdapter&gt; logger)<br>    {<br>        _logger = logger;<br>        var s3  = options.Value.S3;<br>        _client = new AmazonS3Client(<br>            s3.AccessKey,<br>            s3.SecretKey,<br>            RegionEndpoint.GetBySystemName(s3.Region)<br>        );<br>    }<br>    public async Task&lt;string&gt; UploadAsync(<br>        string container, string fileName, Stream content)<br>    {<br>        _logger.LogInformation(&quot;Uploading {File} to S3 bucket {Bucket}&quot;,<br>            fileName, container);<br>        await _client.PutObjectAsync(new PutObjectRequest<br>        {<br>            BucketName  = container,<br>            Key         = fileName,<br>            InputStream = content<br>        });<br>        return $&quot;https://{container}.s3.amazonaws.com/{fileName}&quot;;<br>    }<br>    public async Task&lt;Stream&gt; DownloadAsync(string container, string fileName)<br>    {<br>        var response = await _client.GetObjectAsync(container, fileName);<br>        return response.ResponseStream;<br>    }<br>    public async Task DeleteAsync(string container, string fileName)<br>        =&gt; await _client.DeleteObjectAsync(container, fileName);<br>}</pre><h3>Azure Blob Storage Adapter</h3><pre>public class AzureBlobAdapter : ICloudStorageService<br>{<br>    private readonly BlobServiceClient _client;<br>    private readonly ILogger&lt;AzureBlobAdapter&gt; _logger;<br>    public AzureBlobAdapter(<br>        IOptions&lt;CloudStorageOptions&gt; options,<br>        ILogger&lt;AzureBlobAdapter&gt; logger)<br>    {<br>        _logger = logger;<br>        _client = new BlobServiceClient(options.Value.Azure.ConnectionString);<br>    }<br>    public async Task&lt;string&gt; UploadAsync(<br>        string container, string fileName, Stream content)<br>    {<br>        _logger.LogInformation(&quot;Uploading {File} to Azure container {Container}&quot;,<br>            fileName, container);<br>        var containerClient = _client.GetBlobContainerClient(container);<br>        await containerClient.CreateIfNotExistsAsync();<br>        var blobClient = containerClient.GetBlobClient(fileName);<br>        await blobClient.UploadAsync(content, overwrite: true);<br>        return blobClient.Uri.ToString();<br>    }<br>    public async Task&lt;Stream&gt; DownloadAsync(string container, string fileName)<br>    {<br>        var blob     = _client.GetBlobContainerClient(container).GetBlobClient(fileName);<br>        var response = await blob.DownloadAsync();<br>        return response.Value.Content;<br>    }<br>    public async Task DeleteAsync(string container, string fileName)<br>    {<br>        var blob = _client.GetBlobContainerClient(container).GetBlobClient(fileName);<br>        await blob.DeleteIfExistsAsync();<br>    }<br>}</pre><h3>Google Cloud Storage Adapter</h3><pre>public class GcsStorageAdapter : ICloudStorageService<br>{<br>    private readonly StorageClient _client;<br>    private readonly ILogger&lt;GcsStorageAdapter&gt; _logger;<br>public GcsStorageAdapter(<br>        IOptions&lt;CloudStorageOptions&gt; options,<br>        ILogger&lt;GcsStorageAdapter&gt; logger)<br>    {<br>        _logger = logger;<br>        _       = options.Value.Gcs.ProjectId; // validated at startup<br>        _client = StorageClient.Create();<br>    }<br>    public async Task&lt;string&gt; UploadAsync(<br>        string container, string fileName, Stream content)<br>    {<br>        _logger.LogInformation(&quot;Uploading {File} to GCS bucket {Bucket}&quot;,<br>            fileName, container);<br>        await _client.UploadObjectAsync(container, fileName, null, content);<br>        return $&quot;https://storage.googleapis.com/{container}/{fileName}&quot;;<br>    }<br>    public async Task&lt;Stream&gt; DownloadAsync(string container, string fileName)<br>    {<br>        var stream = new MemoryStream();<br>        await _client.DownloadObjectAsync(container, fileName, stream);<br>        stream.Position = 0;<br>        return stream;<br>    }<br>    public async Task DeleteAsync(string container, string fileName)<br>        =&gt; await _client.DeleteObjectAsync(container, fileName);<br>}</pre><p>Notice the pattern — every adapter takes IOptions&lt;CloudStorageOptions&gt; via constructor injection and reads only the section it needs. The rest of the options object is ignored. Clean, focused, testable.</p><h3>Step 5: Register Everything with a Clean Extension Method</h3><p>Instead of cluttering Program.cs, we wrap all DI registration in a single extension method:</p><pre>public static class CloudStorageExtensions<br>{<br>    public static IServiceCollection AddCloudStorage(<br>        this IServiceCollection services,<br>        IConfiguration configuration)<br>    {<br>        // Register strongly-typed options<br>        services.Configure&lt;CloudStorageOptions&gt;(<br>            configuration.GetSection(CloudStorageOptions.SectionName));<br>// Register as Singleton - SDK clients are thread-safe,<br>        // designed for reuse, and manage their own connection pools<br>        services.AddSingleton&lt;ICloudStorageService&gt;(sp =&gt;<br>        {<br>            // GetRequiredService - fails loudly at startup if options<br>            // are missing, rather than silently returning null at runtime<br>            var options  = sp.GetRequiredService&lt;IOptions&lt;CloudStorageOptions&gt;&gt;();<br>            var provider = options.Value.Provider;<br>            return provider switch<br>            {<br>                &quot;S3&quot;    =&gt; ActivatorUtilities.CreateInstance&lt;S3StorageAdapter&gt;(sp),<br>                &quot;Azure&quot; =&gt; ActivatorUtilities.CreateInstance&lt;AzureBlobAdapter&gt;(sp),<br>                &quot;GCS&quot;   =&gt; ActivatorUtilities.CreateInstance&lt;GcsStorageAdapter&gt;(sp),<br>                _       =&gt; throw new InvalidOperationException(<br>                               $&quot;Unsupported cloud provider: &#39;{provider}&#39;. &quot; +<br>                               $&quot;Valid values: S3, Azure, GCS&quot;)<br>            };<br>        });<br>        return services;<br>    }<br>}</pre><h3>Program.cs — one line</h3><pre>var builder = WebApplication.CreateBuilder(args);<br>builder.Services.AddCloudStorage(builder.Configuration);<br>builder.Services.AddControllers();<br>var app = builder.Build();<br>app.MapControllers();<br>app.Run();</pre><p>That’s it. The entire cloud provider selection, SDK client creation, and options wiring — one method call.</p><h3>Step 6: The Controller — Zero SDK Knowledge</h3><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class FilesController : ControllerBase<br>{<br>    private readonly ICloudStorageService _storage;<br>    private readonly ILogger&lt;FilesController&gt; _logger;<br>public FilesController(<br>        ICloudStorageService storage,<br>        ILogger&lt;FilesController&gt; logger)<br>    {<br>        _storage = storage;<br>        _logger  = logger;<br>    }<br>    [HttpPost(&quot;{container}&quot;)]<br>    public async Task&lt;IActionResult&gt; Upload(string container, IFormFile file)<br>    {<br>        if (file is null || file.Length == 0)<br>            return BadRequest(&quot;No file provided.&quot;);<br>        using var stream = file.OpenReadStream();<br>        var url = await _storage.UploadAsync(container, file.FileName, stream);<br>        _logger.LogInformation(&quot;File {Name} uploaded to {Url}&quot;, file.FileName, url);<br>        return Ok(new { url });<br>    }<br>    [HttpGet(&quot;{container}/{fileName}&quot;)]<br>    public async Task&lt;IActionResult&gt; Download(string container, string fileName)<br>    {<br>        var stream = await _storage.DownloadAsync(container, fileName);<br>        return File(stream, &quot;application/octet-stream&quot;, fileName);<br>    }<br>    [HttpDelete(&quot;{container}/{fileName}&quot;)]<br>    public async Task&lt;IActionResult&gt; Delete(string container, string fileName)<br>    {<br>        await _storage.DeleteAsync(container, fileName);<br>        return NoContent();<br>    }<br>}</pre><p>The controller has absolutely no idea whether it’s talking to AWS, Azure, or Google. It just calls ICloudStorageService. This is exactly what you want.</p><h3>Key Design Decisions Explained</h3><h3>Why AddSingleton and not AddScoped or AddTransient?</h3><p>All three cloud SDKs are explicitly designed to be instantiated once and reused:</p><ul><li>AmazonS3Client — manages a connection pool and credential cache internally</li><li>BlobServiceClient — wraps an HttpClient under the hood; recreating it exhausts ports</li><li>StorageClient — holds auth tokens and gRPC channels</li></ul><p>Using AddTransient rebuilds the entire SDK client on every injection — throwing away connection pools and cached credentials on every request. Using AddScoped is better but still wasteful. AddSingleton is the correct choice because these clients are <strong>stateless and thread-safe</strong> by design.</p><p>The one rule: your adapters must never store request-specific state (user ID, tenant, etc.) as fields. All context should flow through method parameters.</p><h3>Why GetRequiredService and not GetService?</h3><pre>// GetService — returns null silently if not registered<br>var options = sp.GetService&lt;IOptions&lt;CloudStorageOptions&gt;&gt;();<br>options.Value.Provider; // NullReferenceException — hard to trace<br><br>// GetRequiredService - throws immediately with a clear message<br>var options = sp.GetRequiredService&lt;IOptions&lt;CloudStorageOptions&gt;&gt;();<br>// &quot;No service for type &#39;IOptions&lt;CloudStorageOptions&gt;&#39; has been registered.&quot;</pre><p>GetRequiredService follows the <strong>fail-fast principle</strong>. If a required dependency isn&#39;t registered, you want to know at application startup — not when a user tries to upload a file at 2am in production. Use GetService only when a dependency is genuinely optional and you have meaningful fallback logic.</p><h3>Why ActivatorUtilities.CreateInstance over new?</h3><pre>// Using new — you have to manually resolve every dependency<br>new S3StorageAdapter(<br>    sp.GetRequiredService&lt;IOptions&lt;CloudStorageOptions&gt;&gt;(),<br>    sp.GetRequiredService&lt;ILogger&lt;S3StorageAdapter&gt;&gt;()<br>)<br><br>// Using ActivatorUtilities - DI resolves all constructor parameters automatically<br>ActivatorUtilities.CreateInstance&lt;S3StorageAdapter&gt;(sp)</pre><p>ActivatorUtilities.CreateInstance lets .NET&#39;s DI container resolve all the adapter&#39;s constructor dependencies automatically. If you later add ILogger, IMetricsService, or any other dependency to an adapter, the factory code in AddCloudStorage doesn&#39;t need to change.</p><h3>Why the Options Pattern over raw IConfiguration?</h3><p>Raw IConfiguration Options Pattern config[&quot;CloudStorage:S3:AccessKey&quot;] — magic strings Strongly typed options.Value.S3.AccessKey Runtime KeyNotFoundException Compile-time safety No validation support Use [Required], ValidateDataAnnotations() Hard to mock in tests Just pass a concrete CloudStorageOptions</p><p>With the Options Pattern you can also add startup validation:</p><pre>services<br>    .AddOptions&lt;CloudStorageOptions&gt;()<br>    .Bind(configuration.GetSection(CloudStorageOptions.SectionName))<br>    .ValidateDataAnnotations()<br>    .ValidateOnStart(); // fail at startup, not runtime</pre><h3>Testing — the Real Payoff</h3><p>Because the controller depends only on ICloudStorageService, unit testing is trivial:</p><pre>[Fact]<br>public async Task Upload_ReturnsOk_WithFileUrl()<br>{<br>    // Arrange<br>    var mockStorage = new Mock&lt;ICloudStorageService&gt;();<br>    mockStorage<br>        .Setup(s =&gt; s.UploadAsync(&quot;my-bucket&quot;, &quot;test.jpg&quot;, It.IsAny&lt;Stream&gt;()))<br>        .ReturnsAsync(&quot;https://my-bucket.s3.amazonaws.com/test.jpg&quot;);<br><br>var controller = new FilesController(<br>        mockStorage.Object,<br>        Mock.Of&lt;ILogger&lt;FilesController&gt;&gt;());<br>    var fileMock = new Mock&lt;IFormFile&gt;();<br>    fileMock.Setup(f =&gt; f.FileName).Returns(&quot;test.jpg&quot;);<br>    fileMock.Setup(f =&gt; f.Length).Returns(1024);<br>    fileMock.Setup(f =&gt; f.OpenReadStream()).Returns(new MemoryStream());<br>    // Act<br>    var result = await controller.Upload(&quot;my-bucket&quot;, fileMock.Object);<br>    // Assert<br>    var ok    = Assert.IsType&lt;OkObjectResult&gt;(result);<br>    var value = ok.Value as dynamic;<br>    Assert.Equal(&quot;https://my-bucket.s3.amazonaws.com/test.jpg&quot;, value!.url);<br>}</pre><p>No real AWS credentials. No Azure subscription. No network calls. Pure logic, pure speed.</p><h3>Adding a New Provider Is Trivial</h3><p>Say your company signs a deal with Cloudflare R2. Here’s all you need to do:</p><ol><li>Add R2Options to CloudStorageOptions</li><li>Add the R2 section to appsettings.json</li><li>Write R2StorageAdapter : ICloudStorageService</li><li>Add &quot;R2&quot; =&gt; ActivatorUtilities.CreateInstance&lt;R2StorageAdapter&gt;(sp) to the switch</li></ol><p>The controller, the interface, the extension method signature — <strong>none of it changes</strong>. That’s the Open/Closed Principle in action.</p><h3>Summary</h3><p>Here’s what we built and why each piece matters:</p><ul><li><strong>ICloudStorageService</strong> — the single contract that decouples your app from any specific cloud provider</li><li><strong>Adapter classes</strong> — one per provider, each wrapping a different SDK behind the same interface</li><li><strong>CloudStorageOptions</strong> — strongly typed config via the Options Pattern, eliminating magic strings and enabling startup validation</li><li><strong>AddCloudStorage() extension</strong> — clean DI registration, keeps Program.cs lean</li><li><strong>AddSingleton</strong> — correct lifetime for SDK clients that are thread-safe and manage their own connection pools</li><li><strong>GetRequiredService</strong> — fail-fast dependency resolution, surfaces missing registrations at startup</li><li><strong>ActivatorUtilities.CreateInstance</strong> — lets DI resolve adapter dependencies automatically, future-proofing the factory</li></ul><p>The result is a system where switching cloud providers is a config change, adding a new provider is additive only, and every layer is independently testable.</p><h3>Final Code Structure</h3><pre>YourProject/<br>├── Options/<br>│   └── CloudStorageOptions.cs   (S3Options, AzureOptions, GcsOptions)<br>├── Interfaces/<br>│   └── ICloudStorageService.cs<br>├── Adapters/<br>│   ├── S3StorageAdapter.cs<br>│   ├── AzureBlobAdapter.cs<br>│   └── GcsStorageAdapter.cs<br>├── Extensions/<br>│   └── CloudStorageExtensions.cs<br>├── Controllers/<br>│   └── FilesController.cs<br>└── appsettings.json</pre><p>Clean, discoverable, and ready to scale.</p><h3>When Should You Use the Adapter Pattern?</h3><p>The Adapter Pattern is not just for cloud storage. Reach for it whenever you recognize one of these situations in your codebase:</p><p><strong>1. Integrating a third-party or legacy SDK</strong> Any time you pull in an external library — payment gateways (Stripe, Razorpay), SMS providers (Twilio, AWS SNS), email services (SendGrid, Mailgun) — their APIs will never match your domain’s language. Wrap them in an adapter and speak your own language inside your app.</p><pre>// Without Adapter — Stripe leaking into your domain<br>await stripeClient.PaymentIntents.CreateAsync(new PaymentIntentCreateOptions<br>{<br>    Amount   = 99900,           // Stripe uses paise/cents as long<br>    Currency = &quot;inr&quot;,<br>    PaymentMethod = &quot;pm_xyz&quot;<br>});<br>// With Adapter - your domain language<br>await _paymentService.ChargeAsync(amount: 999.00m, currency: &quot;INR&quot;);</pre><p><strong>2. You need to support multiple implementations of the same concept</strong> Multiple cloud providers, multiple payment gateways, multiple SMS vendors, multiple notification channels — whenever “multiple implementations, one interface” is the requirement, Adapter is the answer.</p><p><strong>3. You want to isolate your app from external change</strong> AWS changes their SDK? Only your S3StorageAdapter changes. Twilio updates their API version? Only your TwilioSmsAdapter changes. The rest of your application is completely untouched. This is the real superpower.</p><p><strong>4. You need to make legacy code testable</strong> Old code that was never written with testing in mind can be wrapped in an adapter that implements a mockable interface. Suddenly, years of untestable legacy becomes fully unit-testable without touching a single line of the original.</p><p><strong>5. Working with external APIs that return ugly DTOs</strong> Third-party APIs often return bloated, weirdly named response objects. An adapter can translate their ThirdPartyWeatherApiResponse into your clean WeatherResult domain model in one place.</p><h3>When NOT to Use the Adapter Pattern</h3><p>Like every pattern, the Adapter can be overused. Here are the situations where you should resist the urge:</p><p><strong>1. When you only have one implementation and no plans to add more</strong> If your app will only ever use Azure Blob Storage and there is zero chance of switching, adding an adapter and an interface is unnecessary complexity. YAGNI — You Ain’t Gonna Need It. Build the abstraction when the need is real, not imaginary.</p><p><strong>2. When the two interfaces are almost identical</strong> If the third-party SDK’s method signatures already closely match what you want, a thin wrapper adds boilerplate without value. Just use the SDK directly or write a simple extension method.</p><p><strong>3. When you start creating adapters for adapters</strong> If you find yourself writing MyAdapterAdapter or chaining three layers of translation, that&#39;s a sign the design needs to be rethought. An adapter should be one clean translation layer, not a tower of wrappers.</p><p><strong>4. When the interface you’re adapting to is unstable</strong> If your ICloudStorageService interface is changing every sprint, the adapters will constantly need updating. Stabilize the interface first, then wrap. Premature abstraction costs more than it saves.</p><p><strong>5. Simple internal utility classes</strong> Not everything needs an interface and an adapter. A DateHelper or a StringExtensions class doesn&#39;t benefit from this pattern. Save it for integration points and external boundaries.</p><blockquote><strong><em>Rule of thumb:</em></strong><em> The Adapter Pattern shines at the boundaries of your system — where your code meets the outside world. Inside your own domain logic, keep it simple.</em></blockquote><h3>Wrapping Up</h3><p>The Adapter Pattern is one of the most practical patterns in real-world .NET applications. It helps you:</p><ul><li><strong>Simplify integrations</strong> — talk to any external service through your own clean interface</li><li><strong>Reduce coupling</strong> — your controllers and services never depend on SDK-specific types</li><li><strong>Improve flexibility</strong> — swap providers with a config change, not a code change</li><li><strong>Boost testability</strong> — mock any external dependency without real credentials or network calls</li><li><strong>Future-proof your architecture</strong> — adding a new provider is purely additive, nothing breaks</li></ul><p>Instead of letting external services dictate your architecture — their method names, their parameter types, their response objects — <strong>you take control.</strong> You define the contract, and you make the outside world conform to it.</p><p>The next time you pull in a third-party SDK and start calling it directly from your controller, pause for five minutes. Write the interface you <em>wish</em> existed. Then write the adapter that makes it real.</p><p>That five minutes of upfront thinking will save you weeks of pain down the road. 🚀</p><p>👉 Check the full implementation on GitHub: <a href="https://github.com/CSSinghNet/AdapterPattern">https://github.com/CSSinghNet/AdapterPattern</a></p><p><em>Thanks for reading! If this was helpful, share it with a fellow .NET developer who’s drowning in SDK-specific code. And if you’ve used the Adapter Pattern in an interesting way — drop it in the comments, would love to see it!</em></p><p><em>Tags: #dotnet #csharp #designpatterns #webapi #cleanarchitecture #aws #azure #googlecloud #softwaredevelopment #adapter #solid</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4497d32a59e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB CRUD Operations with .NET 9 Web API — Step-by-Step Guide]]></title>
            <link>https://medium.com/@chandrashekharsingh25/mongodb-crud-operations-with-net-9-web-api-step-by-step-guide-fd1234fc1a1b?source=rss-796c5dd99155------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd1234fc1a1b</guid>
            <dc:creator><![CDATA[Chandrashekhar Singh]]></dc:creator>
            <pubDate>Sat, 03 May 2025 10:08:35 GMT</pubDate>
            <atom:updated>2025-05-03T10:08:35.793Z</atom:updated>
            <content:encoded><![CDATA[<h3>MongoDB CRUD Operations with .NET 9 Web API — Step-by-Step Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*a0seOAFyg0ewjkPMiTRZ4g.jpeg" /><figcaption>Image</figcaption></figure><p>In this blog post, you’ll learn how to create a .NET 9 Web API that can handle basic operations like Create, Read, Update, and Delete (CRUD) using MongoDB.</p><p><strong>Agenda</strong></p><ul><li>Introduction</li><li>MongoDB Features</li><li>MongoDB Basic Concepts</li><li>MongoDB Installation</li><li>Step-by-Step Implementation Using .NET Core Web API</li></ul><p><strong>Prerequisites</strong></p><ul><li>.NET Core 9 SDK</li><li>Visual Studio 2022</li><li>MongoDB</li></ul><p><strong>Introduction</strong></p><ul><li>MongoDB is a general-purpose, document-based NoSQL database built for modern and cloud-based applications.</li><li>It is developed using the C++ programming language.</li><li>MongoDB uses <strong>collections</strong> and <strong>documents</strong> instead of tables and rows.</li><li>It does not use traditional database concepts like schema, table, or SQL queries.</li><li>It can handle any type or size of data due to its flexible structure.</li><li>MongoDB supports <strong>replication</strong>, meaning it keeps multiple copies of the database to ensure data is not lost in case of failure.</li><li>For more details, you can visit the official <a href="https://www.mongodb.com/docs/">MongoDB documentation</a>.</li></ul><p><strong>Features</strong></p><ul><li><strong>Cross-Platform</strong> — Runs on various operating systems like Windows, Linux, and macOS.</li><li><strong>Document-Oriented Database</strong> — Stores data in flexible, JSON-like documents.</li><li><strong>High Scalability and Performance</strong> — Easily handles large amounts of data and traffic.</li><li><strong>High Availability and Durability</strong> — Ensures data reliability through replication and failover support.</li></ul><p><strong>MongoDB Basic Concepts</strong></p><ul><li><strong>Database</strong> — A MongoDB database is a set of collections.</li><li><strong>Collection</strong> — A collection is a group of documents, similar to a table in relational databases but without a fixed schema. Documents in a collection can have different fields.</li><li><strong>Document</strong> — A document is a set of key-value pairs with a dynamic structure, meaning each document can have different fields and types of data.</li><li><strong>Indexes</strong> — MongoDB uses indexes to optimize query execution and improve the speed of data retrieval.</li><li><strong>Replica Sets</strong> — A replica set in MongoDB creates multiple copies of data to ensure high availability. It continuously replicates data across instances.</li><li><strong>Sharding</strong> — Sharding is a technique used to distribute large datasets across multiple clusters for better scalability and high throughput.</li></ul><p><strong>MongoDB Installation</strong>:</p><ul><li>Follow the instructions in the official MongoDB installation guide to install MongoDB on your machine:<br> <a href="https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-windows/">MongoDB Installation Guide for Windows</a></li><li>After installation, open <strong>MongoDB Compass</strong> and create a new connection with the following URL:<br> mongodb://localhost:27017</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s41YurxXPla_rCubvSGFyw.png" /><figcaption>DB</figcaption></figure><p><strong>Step-by-step implementation using .NET Core Web API</strong></p><ol><li><strong>Create a New .NET Core Web API Project</strong></li></ol><ul><li>Open Visual Studio.</li><li>Create a new project and select <strong>ASP.NET Core Web API</strong> template.</li></ul><p>2. <strong>Install the following NuGet packages.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/0*lP5nxFwYw1agAzvI.png" /></figure><p>3.<strong> Configure MongoDB in appsettings.json</strong></p><p>Open the <strong>appsettings.json</strong> file and add the MongoDB server URL, database name, and collection name after you have created them in MongoDB Compass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*Qr1dClvtaN-KLlPzlKkFjw.png" /><figcaption>appsetting.json_img</figcaption></figure><p>4. Register a few services inside the Program class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMq50O17Auk1oAQyAg2GDw.png" /><figcaption>program</figcaption></figure><p>5. Create a new Product Details class.</p><pre>using MongoDB.Bson.Serialization.Attributes;<br>using MongoDB.Bson;<br><br>namespace MongoDbDemo.Entities<br>{<br>    public class ProductDetails<br>    {<br>        [BsonId]<br>        [BsonRepresentation(BsonType.ObjectId)]<br>        public string Id { get; set; }<br>        [BsonElement(&quot;ProductName&quot;)]<br>        public string ProductName { get; set; }<br>        public string ProductDescription { get; set; }<br>        public int ProductPrice { get; set; }<br>        public int ProductStock { get; set; }<br>    }<br>}</pre><p>6. Next add the Product DB Settings class.</p><pre>namespace MongoDbDemo.Configurations<br>{<br>    public class ProductDBSettings<br>    {<br>        public string ConnectionString { get; set; }<br>        public string DatabaseName { get; set; }<br>        public string ProductCollectionName { get; set; }<br>    }<br>}</pre><p>7. Create a new IProductService and IProductService inside the repositories folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUftirgIYXt4nuTGug_TVA.png" /><figcaption>IProductService</figcaption></figure><p>ProductService:</p><pre>using Microsoft.Extensions.Options;<br>using MongoDB.Driver;<br>using MongoDbDemo.Configurations;<br>using MongoDbDemo.Entities;<br><br>namespace MongoDbDemo.Repositories<br>{<br>    public class ProductService :IProductService<br>    {<br>        private readonly IMongoCollection&lt;ProductDetails&gt; productCollection;<br><br>        public ProductService(<br>         IOptions&lt;ProductDBSettings&gt; productDatabaseSetting)<br>        {<br>            var mongoClient = new MongoClient(<br>                productDatabaseSetting.Value.ConnectionString);<br><br>            var mongoDatabase = mongoClient.GetDatabase(<br>                productDatabaseSetting.Value.DatabaseName);<br><br>            productCollection = mongoDatabase.GetCollection&lt;ProductDetails&gt;(<br>                productDatabaseSetting.Value.ProductCollectionName);<br>        }<br><br>        public async Task&lt;List&lt;ProductDetails&gt;&gt; ProductListAsync()<br>        {<br>            return await productCollection.Find(_ =&gt; true).ToListAsync();<br>        }<br><br>        public async Task&lt;ProductDetails&gt; GetProductDetailByIdAsync(string productId)<br>        {<br>            return await productCollection.Find(x =&gt; x.Id == productId).FirstOrDefaultAsync();<br>        }<br><br>        public async Task AddProductAsync(ProductDetails productDetails)<br>        {<br>            await productCollection.InsertOneAsync(productDetails);<br>        }<br><br>        public async Task UpdateProductAsync(string productId, ProductDetails productDetails)<br>        {<br>             await productCollection.ReplaceOneAsync(x =&gt; x.Id == productId, productDetails);<br>        }<br><br>        public async Task DeleteProductAsync(string productId)<br>        {<br>            await productCollection.DeleteOneAsync(x =&gt; x.Id == productId);<br>        }<br>    }<br>}</pre><p>8. add a product controller.</p><pre>using Microsoft.AspNetCore.Mvc;<br>using MongoDbDemo.Entities;<br>using MongoDbDemo.Repositories;<br><br>namespace MongoDbDemo.Controllers<br>{<br>    [Route(&quot;api/[controller]&quot;)]<br>    [ApiController]<br>    public class ProductsController : ControllerBase<br>    {<br>        private readonly IProductService productService;<br><br>        public ProductsController(IProductService productService) =&gt;<br>            this.productService = productService;<br><br>        [HttpGet]<br>        public async Task&lt;List&lt;ProductDetails&gt;&gt; Get()<br>        {<br>            return await productService.ProductListAsync();<br>        }<br><br>        [HttpGet(&quot;{productId:length(24)}&quot;)]<br>        public async Task&lt;ActionResult&lt;ProductDetails&gt;&gt; Get(string productId)<br>        {<br>            var productDetails = await productService.GetProductDetailByIdAsync(productId);<br><br>            if (productDetails is null)<br>            {<br>                return NotFound();<br>            }<br><br>            return productDetails;<br>        }<br><br>        [HttpPost]<br>        public async Task&lt;IActionResult&gt; Post(ProductDetails productDetails)<br>        {<br>            await productService.AddProductAsync(productDetails);<br><br>            return CreatedAtAction(nameof(Get), new { id = productDetails.Id }, productDetails);<br>        }<br><br>        [HttpPut(&quot;{productId:length(24)}&quot;)]<br>        public async Task&lt;IActionResult&gt; Update(string productId, ProductDetails productDetails)<br>        {<br>            var productDetail = await productService.GetProductDetailByIdAsync(productId);<br><br>            if (productDetail is null)<br>            {<br>                return NotFound();<br>            }<br><br>            productDetails.Id = productDetail.Id;<br><br>            await productService.UpdateProductAsync(productId, productDetails);<br><br>            return Ok();<br>        }<br><br>        [HttpDelete(&quot;{productId:length(24)}&quot;)]<br>        public async Task&lt;IActionResult&gt; Delete(string productId)<br>        {<br>            var productDetails = await productService.GetProductDetailByIdAsync(productId);<br><br>            if (productDetails is null)<br>            {<br>                return NotFound();<br>            }<br><br>            await productService.DeleteProductAsync(productId);<br><br>            return Ok();<br>        }<br>    }<br>}</pre><p>9. Run the application and add some product details using swagger UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R8Yk0SSuz6u3-YsxvBdM_Q.png" /><figcaption>swagger</figcaption></figure><p><strong>10. </strong>Once you’ve added some product data, you’ll be able to view the details in MongoDB Compass as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lztWzWRKUrpS78AuakiEBw.png" /></figure><p><strong>GitHub URL-</strong></p><p><a href="https://github.com/CSSinghNet/MongoDbDemo">GitHub - CSSinghNet/MongoDbDemo</a></p><p><strong>Conclusion-</strong></p><p>You’ve just built a complete <strong>MongoDB CRUD API using .NET Core 9 Web API</strong>! This is a solid foundation for building scalable backend services that interact with MongoDB databases.</p><p>Happy Coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd1234fc1a1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering TypeScript: 10 Advanced Techniques for Expert Developers]]></title>
            <link>https://medium.com/@chandrashekharsingh25/mastering-typescript-10-advanced-techniques-for-expert-developers-70353dd9a7db?source=rss-796c5dd99155------2</link>
            <guid isPermaLink="false">https://medium.com/p/70353dd9a7db</guid>
            <dc:creator><![CDATA[Chandrashekhar Singh]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 04:12:15 GMT</pubDate>
            <atom:updated>2024-04-07T04:12:15.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*zaNnWtkJKkvzo0vd.jpg" /></figure><ol><li><strong>Conditional Types</strong> : It enable the creation of dynamic type structures, adapting shape based on conditions. For instance, they allow defining <strong>object</strong> types with specific properties depending on a provided string value..</li></ol><pre>type Config = {<br>  type: &#39;basic&#39; | &#39;advanced&#39;;<br>  // ... other properties<br>};<br><br>type BasicConfig = Config &amp; { type: &#39;basic&#39; };<br>type AdvancedConfig = Config &amp; { type: &#39;advanced&#39; };<br><br>function configure(config: Config): void {<br>  if (config.type === &#39;basic&#39;) {<br>    console.log(&#39;Applying basic configuration&#39;);<br>    // config is now of type BasicConfig<br>  } else {<br>    console.log(&#39;Applying advanced configuration&#39;);<br>    // config is now of type AdvancedConfig<br>  }<br>}</pre><p>2. <strong>Template Literal Types :- It </strong>empower developers to construct sophisticated string types by incorporating dynamic expressions enclosed within backticks. They are particularly useful for modeling API responses, URL structures, or validation formats.</p><pre>type Endpoint = `/users/${number}`;<br><br>const validEndpoint: Endpoint = &#39;/users/123&#39;;<br><br>// const invalidEndpoint: Endpoint = &#39;/posts/456&#39;; // Error: Type &#39;&quot;/posts/456&quot;&#39; is not assignable to type &#39;Endpoint&#39;</pre><p>3. <strong>Higher-Order Types (HOTs) :-</strong> harness functions capable of accepting and returning types, enabling advanced abstractions such as generic type predicates and type constructors.</p><pre>type IsStringLiteral&lt;T&gt; = T extends string ? true : false;<br><br>function logIfString&lt;T&gt;(value: T): T extends string ? void : T {<br>  if (IsStringLiteral&lt;T&gt;) {<br>    console.log(value);<br>  }<br>  return value;<br>}</pre><p>4. <strong>Mapped Types :- </strong>It<strong> </strong>allow you to change existing types by performing operations on each property. They’re handy for tasks like adding prefixes or suffixes to properties and creating key-value pairs from objects.</p><pre>interface User {<br>  name: string;<br>  age: number;<br>}<br><br>type ReadOnly&lt;T&gt; = { readonly [P in keyof T]: T[P] };<br><br>const readOnlyUser: ReadOnly&lt;User&gt; = {<br>  name: &#39;John Doe&#39;,<br>  age: 30<br>};<br><br>// readOnlyUser.name = &#39;Jane Doe&#39;; // Error: Cannot assign to &#39;name&#39; because it is a read-only property</pre><p>5. <strong>Recursive Types :- </strong>It<strong> </strong>enable defining types that refer to themselves, making it possible to build intricate data structures such as linked lists or trees.</p><pre>interface LinkedList&lt;T&gt; {<br>  value: T;<br>  next?: LinkedList&lt;T&gt;;<br>}<br><br>const numbersList: LinkedList&lt;number&gt; = {<br>  value: 1,<br>  next: {<br>    value: 2,<br>    next: {<br>      value: 3,<br>      next: null<br>    }<br>  }<br>};</pre><p>6. <strong>Unions and Intersections : </strong>It<strong> </strong>allow you to merge multiple types using the | and &amp; operators. They represent values that can be either one type, both types simultaneously, or a combination of types.</p><pre>type NumberOrString = number | string;<br><br>const value: NumberOrString = 123; // or value = &quot;hello&quot;<br><br>type Point = { x: number, y: number };<br>type LabeledPoint = Point &amp; { label: string };</pre><p>7. <strong>Type Aliases :- </strong>It provide the ability to define custom names for complex types, enhancing code readability and maintainability.</p><pre>type UserResponse = {<br>  id: number;<br>  username: string;<br>  email: string;<br>};<br><br>function fetchUser(): UserResponse {<br>  // ...<br>}</pre><p>8. <strong>Type Guards :- </strong>enable developers to refine the type of a variable within conditional statements, utilizing assertions such as <strong>typeof</strong> checks or custom functions.</p><pre>function isNumber(value: NumberOrString): value is number {<br>  return typeof value === &#39;number&#39;;<br>}<br><br>if (isNumber(value)) {<br>  console.log(&#39;Value is a number:&#39;, value);<br>} else {<br>  console.log(&#39;Value is a string:&#39;, value);<br>}</pre><p>9. <strong>Decorators :- </strong>Extend the behavior of classes, properties, and methods with custom logic, enabling features like dependency injection, validation, or performance optimization.</p><pre>function Log(target: any, key: string, descriptor: PropertyDescriptor) {<br>  const originalMethod = descriptor.value;<br>  descriptor.value = function (...args: any[]) {<br>    console.log(`Calling ${key}()`);<br>    return originalMethod.apply(this, args);<br>  };<br>}<br><br>class MyClass {<br>  @Log<br>  greet() {<br>    console.log(&#39;Hello!&#39;);<br>  }<br>}</pre><p>10. <strong>Utility Types :-</strong> Utilize built-in and community-defined utilities like <strong>Pick</strong>, <strong>Omit</strong>, or <strong>Partial</strong> to manipulate the structure of existing types without manual effort.</p><pre>interface User {<br>    id: number;<br>    name: string;<br>    email: string;<br>    age: number;<br>}<br><br>// Pick: Create a new type by selecting specific properties from an existing type<br>type UserSummary = Pick&lt;User, &#39;id&#39; | &#39;name&#39;&gt;;<br><br>const userSummary: UserSummary = {<br>    id: 1,<br>    name: &#39;John Doe&#39;<br>};<br><br>// Omit: Create a new type by excluding specific properties from an existing type<br>type UserWithoutAge = Omit&lt;User, &#39;age&#39;&gt;;<br><br>const userWithoutAge: UserWithoutAge = {<br>    id: 2,<br>    name: &#39;Jane Smith&#39;,<br>    email: &#39;jane@example.com&#39;<br>};<br><br>// Partial: Make all properties of a type optional<br>type PartialUser = Partial&lt;User&gt;;<br><br>const partialUser: PartialUser = {<br>    id: 3<br>};</pre><p><strong>Bonus:</strong> Dive into advanced TypeScript features like the <strong>keyof</strong> operator, discriminated unions, generics combined with conditional types, and sophisticated generics patterns.</p><p><strong>Keep in mind: </strong>Apply these advanced features to enhance code clarity, not just add complexity. Strive for a balance between power and readability, ensuring your code remains maintainable.</p><p>I trust these techniques will enrich your TypeScript skills and encourage you to craft code that is both robust and expressive!</p><p><strong>Thanks for reading !!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70353dd9a7db" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>