DEV Community

Manohari Jayachandran
Manohari Jayachandran

Posted on Edited on

C# Mid-Level Day 4 (Part 2): IDisposable, JSON, Unit Testing and Dependency Injection, With Four Practice Projects

Why this post exists

This is Part 2 of Day 4 in my six-day C# deep dive. Part 1 covered extension methods, pattern matching and records. This post covers the tools that make real programs reliable: cleaning up resources with IDisposable, JSON, unit testing, and dependency injection.

Each concept has what it is, an analogy, a short example, a practice question and a complete solution with the reasons it is written that way. Concepts 10 to 13 continue the numbering from Part 1. Try each practice question yourself before reading the solution.

All code targets .NET 8 or later. Most examples use top-level statements, so you can paste them into the Program.cs of a new console project. The testing section uses a small library project plus a test project, and each file is labelled.

Concept 10: IDisposable, using and resource cleanup

What it is. Memory is cleaned up automatically by the garbage collector, but some resources are not just memory: file handles, database connections, network sockets. They are limited, they can stay locked, and the garbage collector decides when to clean up, which could be seconds or minutes later. A class that holds such a resource implements IDisposable, and callers release it deterministically with a using statement.

The analogy: a hotel key card. The garbage collector is a cleaner who tidies the rooms at unpredictable times. If you leave the hotel without returning your key, the room stays unavailable to other guests until the cleaner eventually notices. Dispose is handing back the key at the front desk the moment you leave. using is the checkout slot that does it for you, even if you leave in a hurry because something went wrong.

using (var a = new Tracer("A"))                       // using block: Dispose runs at the closing brace
{
    Console.WriteLine("working in A");
}

using var b = new Tracer("B");                        // using declaration: Dispose runs at the end of the scope
Console.WriteLine("working in B (it stays open until the program ends)");

try
{
    using var c = new Tracer("C");
    throw new InvalidOperationException("boom");      // C is still disposed on the way out
}
catch (InvalidOperationException ex)
{
    Console.WriteLine($"caught: {ex.Message}");
}

Console.WriteLine("end of the program");

class Tracer : IDisposable
{
    private readonly string _name;

    public Tracer(string name)
    {
        _name = name;
        Console.WriteLine($"  open {_name}");
    }

    public void Dispose() => Console.WriteLine($"  close {_name}");
}
Enter fullscreen mode Exit fullscreen mode

Output:

  open A
working in A
  close A
  open B
working in B (it stays open until the program ends)
  open C
  close C
caught: boom
end of the program
  close B
Enter fullscreen mode Exit fullscreen mode

What is happening here:

  • A using block disposes the object at the closing brace. A using declaration (using var b = ...) disposes it at the end of the enclosing scope, with less nesting.
  • using is shorthand for try { ... } finally { x.Dispose(); }, which is why C was still closed after the exception.
  • Multiple resources dispose in reverse order of creation, like unwinding a stack.
  • For asynchronous cleanup, implement IAsyncDisposable and use await using.
  • Disposing is separate from the object's memory. After Dispose the object still exists, but it should refuse to be used.

Practice question 10: wrap a file in a correct dispose pattern

Wrap a file (or a connection) in a class that implements the dispose pattern correctly.

Solution

string path = Path.Combine(Path.GetTempPath(), "day4-logfile.txt");

Console.WriteLine("-- the file is flushed and closed when the block ends --");
using (var log = new LogFile(path))
{
    log.Write("first");
    log.Write("second");
}
Console.WriteLine($"lines on disk: {File.ReadAllLines(path).Length}");

Console.WriteLine("-- use after dispose --");
var closed = new LogFile(path);
closed.Dispose();
try { closed.Write("too late"); }
catch (ObjectDisposedException ex) { Console.WriteLine($"ObjectDisposedException for {ex.ObjectName}"); }

Console.WriteLine("-- dispose twice --");
closed.Dispose();
Console.WriteLine("no error");

Console.WriteLine("-- nested usings dispose in reverse order --");
using (var outer = new Connection("outer"))
using (var inner = new Connection("inner"))
{
    Console.WriteLine("  working");
}

Console.WriteLine("-- an exception still disposes --");
try
{
    using var risky = new Connection("risky");
    throw new InvalidOperationException("boom");
}
catch (InvalidOperationException ex)
{
    Console.WriteLine($"  caught: {ex.Message}");
}

Console.WriteLine("-- the full pattern, for a class others will inherit from --");
using (var audited = new AuditedFile(path))
{
    audited.Write("hello");
}

// Recommended default: a sealed class that owns only managed resources
public sealed class LogFile : IDisposable
{
    private readonly StreamWriter _writer;
    private bool _disposed;

    public LogFile(string path) => _writer = new StreamWriter(path);

    public void Write(string message)
    {
        ObjectDisposedException.ThrowIf(_disposed, this);
        _writer.WriteLine(message);
    }

    public void Dispose()
    {
        if (_disposed) return;          // safe to call more than once
        _disposed = true;
        _writer.Dispose();
    }
}

public sealed class Connection : IDisposable
{
    private readonly string _name;

    public Connection(string name)
    {
        _name = name;
        Console.WriteLine($"  open {_name}");
    }

    public void Dispose() => Console.WriteLine($"  close {_name}");
}

// The full pattern: only needed when the class is NOT sealed (or holds an unmanaged resource directly)
public class ManagedFile : IDisposable
{
    private StreamWriter? _writer;
    private bool _disposed;

    public ManagedFile(string path) => _writer = new StreamWriter(path, append: true);

    public void Write(string message)
    {
        ObjectDisposedException.ThrowIf(_disposed, this);
        _writer!.WriteLine(message);
    }

    public void Dispose()
    {
        Dispose(disposing: true);
        GC.SuppressFinalize(this);      // no finalizer needed now, but a subclass may add one
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_disposed) return;
        if (disposing)
        {
            _writer?.Dispose();         // managed resources are released only on the explicit path
            _writer = null;
        }
        _disposed = true;
    }
}

public class AuditedFile : ManagedFile
{
    public AuditedFile(string path) : base(path) { }

    protected override void Dispose(bool disposing)
    {
        if (disposing) Console.WriteLine("  AuditedFile cleaning up");
        base.Dispose(disposing);         // always call the base so its resources are released
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

-- the file is flushed and closed when the block ends --
lines on disk: 2
-- use after dispose --
ObjectDisposedException for LogFile
-- dispose twice --
no error
-- nested usings dispose in reverse order --
  open outer
  open inner
  working
  close inner
  close outer
-- an exception still disposes --
  open risky
  close risky
  caught: boom
-- the full pattern, for a class others will inherit from --
  AuditedFile cleaning up
Enter fullscreen mode Exit fullscreen mode

Why this is the best way to write it:

  1. LogFile is the recommended default: sealed, with a simple Dispose. If a class owns only managed resources (like a StreamWriter) and nobody can inherit from it, the one-method version is all you need. No finalizer, no Dispose(bool).
  2. Dispose is safe to call twice. The _disposed flag makes the second call do nothing, which the output confirms. This matters because using and a manual Dispose can both run.
  3. Use after dispose throws ObjectDisposedException. ObjectDisposedException.ThrowIf is the one-line standard guard, so a bug shows up as a clear error at the use site and not as a confusing failure from the underlying stream.
  4. Disposing the writer flushes it. The file has both lines on disk the moment the using block ends. Without it, buffered data can be lost.
  5. The full pattern is for unsealed classes. Dispose(bool disposing) lets a subclass add its own cleanup (see AuditedFile) while the base class still guarantees its own. The subclass must call base.Dispose(disposing).
  6. GC.SuppressFinalize(this) is in the public Dispose because subclasses may add a finalizer later. It tells the runtime the object needs no finalization, since cleanup has already happened.
  7. You almost never write a finalizer. A finalizer is only for a class that directly holds an unmanaged handle. Wrapping a StreamWriter (which already handles its own cleanup) never needs one.
  8. The caller owns the lifetime with using. The class design makes the correct usage easy, and the examples show that disposal order and exceptions are both handled.

Concept 11: JSON with System.Text.Json (custom converters and options)

What it is. JSON is the standard text format for exchanging data. Serialization turns an object into JSON text, and deserialization turns JSON text back into an object. System.Text.Json is the built-in, fast serializer in .NET. JsonSerializerOptions controls naming, formatting and enums, and a custom converter takes over when the default behaviour is not enough, as with polymorphic types.

The analogy: flat-pack furniture. Serializing is taking the finished wardrobe apart and putting the parts in a box with a parts list. Deserializing is assembling it again from the box. For a product that comes in several models, the box needs a label saying which model it is (a type discriminator), or the person assembling has no idea which instructions to use. A custom converter is the person who reads that label.

using System.Text.Json;
using System.Text.Json.Serialization;

var options = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,                 // Name -> name
    WriteIndented = true,
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,      // leave out null properties
    Converters = { new JsonStringEnumConverter() }                     // "Admin", not 2
};

var user = new User("Asha", 30, Role.Admin, null);
string json = JsonSerializer.Serialize(user, options);
Console.WriteLine(json);

User? back = JsonSerializer.Deserialize<User>(json, options);
Console.WriteLine($"Round trip equal: {back == user}");

// Reading is case-sensitive unless you ask otherwise
var web = new JsonSerializerOptions(JsonSerializerDefaults.Web) { Converters = { new JsonStringEnumConverter() } };
User? loose = JsonSerializer.Deserialize<User>("""{"NAME":"Ravi","age":41,"role":"User"}""", web);
Console.WriteLine(loose);

// Bad input throws JsonException
try { JsonSerializer.Deserialize<User>("{ not json }", options); }
catch (JsonException) { Console.WriteLine("JsonException: that is not valid JSON"); }

// Attributes control individual properties
var account = new Account { Id = "a1", PasswordHash = "secret", Name = "Asha" };
Console.WriteLine(JsonSerializer.Serialize(account));

// Built-in polymorphism: a discriminator property says which subtype to build
Animal[] animals = { new Dog("Rex"), new Cat("Tom", 9) };
string animalJson = JsonSerializer.Serialize(animals);
Console.WriteLine(animalJson);
Animal[]? restored = JsonSerializer.Deserialize<Animal[]>(animalJson);
Console.WriteLine(string.Join(", ", restored!.Select(a => a.GetType().Name)));

enum Role { User, Moderator, Admin }

record User(string Name, int Age, Role Role, string? Nickname);

class Account
{
    public string Id { get; set; } = "";

    [JsonIgnore]                                          // never written out
    public string PasswordHash { get; set; } = "";

    [JsonPropertyName("display_name")]                    // a different name in the JSON
    public string Name { get; set; } = "";
}

[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]
[JsonDerivedType(typeof(Dog), "dog")]
[JsonDerivedType(typeof(Cat), "cat")]
abstract record Animal(string Name);

sealed record Dog(string Name) : Animal(Name);

sealed record Cat(string Name, int Lives) : Animal(Name);
Enter fullscreen mode Exit fullscreen mode

Output:

{
  "name": "Asha",
  "age": 30,
  "role": "Admin"
}
Round trip equal: True
User { Name = Ravi, Age = 41, Role = User, Nickname =  }
JsonException: that is not valid JSON
{"Id":"a1","display_name":"Asha"}
[{"kind":"dog","Name":"Rex"},{"kind":"cat","Lives":9,"Name":"Tom"}]
Dog, Cat
Enter fullscreen mode Exit fullscreen mode

What is happening here:

  • JsonSerializerOptions is where policy lives: camelCase names, indentation, skipping nulls, and JsonStringEnumConverter so enums read "Admin" and not 2. Create the options once and reuse them, because building options repeatedly is slow.
  • Reading is case-sensitive by default. JsonSerializerDefaults.Web turns on case-insensitive matching, which is why "NAME" still worked.
  • Bad JSON throws JsonException. Never assume incoming JSON is valid.
  • [JsonIgnore] leaves a property out and [JsonPropertyName] renames it, so the JSON shape can differ from your C# shape.
  • [JsonPolymorphic] with [JsonDerivedType] is the built-in way to handle a base type with a few known subtypes. The kind property tells the deserializer which subtype to create.
  • Positional records deserialize through their constructor, so immutable records work without extra code.

Practice question 11: a polymorphic list of shapes with a custom converter

Serialize and deserialize a polymorphic list of shapes (circles, rectangles, triangles) using a custom converter.

Solution

using System.Text.Json;
using System.Text.Json.Serialization;

var options = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    Converters = { new ShapeConverter() }
};

List<Shape> shapes = [new Circle(2), new Rectangle(3, 4), new Triangle(6, 5)];

string json = JsonSerializer.Serialize(shapes, options);
Console.WriteLine(json);

List<Shape> restored = JsonSerializer.Deserialize<List<Shape>>(json, options)!;
foreach (Shape shape in restored)
{
    Console.WriteLine($"{shape.GetType().Name,-10} area {shape.Area():F2}");
}
Console.WriteLine($"Round trip equal: {shapes.SequenceEqual(restored)}");

Console.WriteLine();
foreach (string bad in new[] { """[{"type":"hexagon","side":2}]""", """[{"radius":2}]""" })
{
    try { JsonSerializer.Deserialize<List<Shape>>(bad, options); }
    catch (JsonException ex) { Console.WriteLine($"JsonException: {ex.Message}"); }
}

public abstract record Shape
{
    public abstract double Area();
}

public sealed record Circle(double Radius) : Shape
{
    public override double Area() => Math.PI * Radius * Radius;
}

public sealed record Rectangle(double Width, double Height) : Shape
{
    public override double Area() => Width * Height;
}

public sealed record Triangle(double Base, double Height) : Shape
{
    public override double Area() => 0.5 * Base * Height;
}

public sealed class ShapeConverter : JsonConverter<Shape>
{
    public override Shape Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        using JsonDocument document = JsonDocument.ParseValue(ref reader);
        JsonElement root = document.RootElement;

        if (!root.TryGetProperty("type", out JsonElement typeElement))
        {
            throw new JsonException("Shape is missing the \"type\" property.");
        }

        return typeElement.GetString() switch
        {
            "circle" => root.Deserialize<Circle>(options)!,
            "rectangle" => root.Deserialize<Rectangle>(options)!,
            "triangle" => root.Deserialize<Triangle>(options)!,
            string other => throw new JsonException($"Unknown shape type \"{other}\"."),
            null => throw new JsonException("Shape \"type\" must be a string.")
        };
    }

    public override void Write(Utf8JsonWriter writer, Shape value, JsonSerializerOptions options)
    {
        string type = value switch
        {
            Circle => "circle",
            Rectangle => "rectangle",
            Triangle => "triangle",
            _ => throw new JsonException($"Cannot serialize {value.GetType().Name}.")
        };

        writer.WriteStartObject();
        writer.WriteString("type", type);                                   // the discriminator goes first

        // Serialize the concrete type with the default rules, then copy its properties across
        using JsonDocument body = JsonSerializer.SerializeToDocument(value, value.GetType(), options);
        foreach (JsonProperty property in body.RootElement.EnumerateObject())
        {
            property.WriteTo(writer);
        }
        writer.WriteEndObject();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

[{"type":"circle","radius":2},{"type":"rectangle","width":3,"height":4},{"type":"triangle","base":6,"height":5}]
Circle     area 12.57
Rectangle  area 12.00
Triangle   area 15.00
Round trip equal: True

JsonException: Unknown shape type "hexagon".
JsonException: Shape is missing the "type" property.
Enter fullscreen mode Exit fullscreen mode

Why this is the best way to write it:

  1. A type discriminator makes the JSON self-describing. Without it, {"radius":2} and {"width":3} can only be told apart by guessing from the property names, which breaks the moment two shapes share one.
  2. Read uses JsonDocument to look ahead. It parses the object once, reads type, then hands the same element to the default deserializer for the concrete type. You never write per-property parsing by hand.
  3. Write also reuses the default behaviour. It writes type first, serializes the concrete type to a document and copies its properties across. So camelCase naming and any other options apply automatically to every shape.
  4. The converter is registered through options.Converters. It handles Shape only, so when it serializes a Circle the default rules apply to it and there is no infinite recursion.
  5. Bad data produces clear JsonException messages. An unknown type and a missing discriminator are both reported with the problem named, not as a null reference deep inside the code.
  6. Shapes are sealed records, so the round trip compares equal (SequenceEqual is true), a quick way to check that nothing was lost.
  7. Know the alternative. When you control the types and the discriminator values are fixed, [JsonPolymorphic] and [JsonDerivedType] (shown in the example above) do the same job with no converter at all. Write a converter when you need custom rules: legacy formats, a discriminator that is not a property, or fallbacks for unknown types.

Concept 12: Unit testing with xUnit (and mocking dependencies)

What it is. A unit test is a small program that runs a piece of your code and checks the result. A test suite catches regressions automatically, and it gives you the confidence to refactor. xUnit is the most widely used .NET test framework. Tests are methods marked [Fact] (one scenario) or [Theory] with [InlineData] (the same scenario with many inputs). A test double is a stand-in for a real dependency such as an email sender or a clock.

The analogy: a crash-test lab. Each test is a controlled experiment: set the stage (Arrange), crash the car (Act), measure the dummy (Assert). A test double is a stunt double: when the scene would send a real email or call a real bank, you use a stand-in that looks the same, does nothing dangerous and writes down exactly what was asked of it.

Set up a test project like this:

dotnet new xunit -n Shop.Tests
cd Shop.Tests
dotnet add reference ../Shop/Shop.csproj
dotnet test
Enter fullscreen mode Exit fullscreen mode
// ===== Calculator.cs =====
public class Calculator
{
    public int Add(int a, int b) => a + b;

    public double Divide(double a, double b)
    {
        if (b == 0) throw new DivideByZeroException("Cannot divide by zero.");
        return a / b;
    }
}
Enter fullscreen mode Exit fullscreen mode
// ===== CalculatorTests.cs =====
using Xunit;

public class CalculatorTests
{
    private readonly Calculator _calculator = new();     // xUnit creates a NEW instance of this class for every test

    [Fact]                                               // one scenario, one set of inputs
    public void Add_TwoNumbers_ReturnsTheirSum()
    {
        // Arrange
        int a = 2, b = 3;

        // Act
        int result = _calculator.Add(a, b);

        // Assert
        Assert.Equal(5, result);
    }

    [Theory]                                             // one scenario, many sets of inputs
    [InlineData(1, 2, 3)]
    [InlineData(-1, 1, 0)]
    [InlineData(0, 0, 0)]
    public void Add_ManyInputs_ReturnsExpectedSum(int a, int b, int expected)
    {
        Assert.Equal(expected, _calculator.Add(a, b));
    }

    [Fact]
    public void Divide_TwoNumbers_ReturnsQuotient()
    {
        Assert.Equal(2.5, _calculator.Divide(5, 2));
    }

    [Fact]
    public void Divide_ByZero_ThrowsWithClearMessage()
    {
        var exception = Assert.Throws<DivideByZeroException>(() => _calculator.Divide(1, 0));

        Assert.Equal("Cannot divide by zero.", exception.Message);
    }
}
Enter fullscreen mode Exit fullscreen mode

dotnet test finishes with a summary like this (plus a duration and the assembly name):

Passed! - Failed: 0, Passed: 6, Skipped: 0, Total: 6
Enter fullscreen mode Exit fullscreen mode

What is happening here:

  • Arrange, Act, Assert is the shape of nearly every good test: build the inputs, call the code once, check the outcome.
  • xUnit creates a new instance of the test class for every test. Fields like _calculator therefore start fresh each time, and tests cannot affect each other through shared state. Use the constructor for setup and IDisposable for cleanup.
  • [Theory] plus [InlineData] runs one method once per row. The three Add rows are three separate test cases in the report.
  • Assert.Throws<T> returns the exception, so you can also check its message. It requires the exact type, not a derived one.
  • Name tests as Method_Scenario_ExpectedResult. A failing test then explains itself in the report.

Practice question 12: tests for Repository and a service with a mocked dependency

Write tests for your Repository<T> and for one service that depends on other things (an email sender and a clock), using test doubles for the dependencies.

Solution

First, the code under test: the repository from Day 3 and a ReminderService that emails customers about overdue invoices. It never talks to a real mail server or reads the real clock directly. It asks for an IEmailSender and an IClock.

// ===== Domain.cs =====
namespace Shop;

public interface IEntity
{
    int Id { get; }
}

public interface IRepository<T> where T : class, IEntity
{
    void Add(T item);
    T? Get(int id);
    bool Remove(int id);
    IReadOnlyList<T> GetAll();
}

public class InMemoryRepository<T> : IRepository<T> where T : class, IEntity
{
    private readonly Dictionary<int, T> _items = new();

    public void Add(T item)
    {
        ArgumentNullException.ThrowIfNull(item);
        if (!_items.TryAdd(item.Id, item))
        {
            throw new InvalidOperationException($"A {typeof(T).Name} with id {item.Id} already exists.");
        }
    }

    public T? Get(int id) => _items.GetValueOrDefault(id);

    public bool Remove(int id) => _items.Remove(id);

    public IReadOnlyList<T> GetAll() => _items.Values.ToList();
}

public record Customer(int Id, string Name, string Email) : IEntity;

public record Invoice(int Id, int CustomerId, decimal Amount, DateOnly DueDate, bool Paid) : IEntity;

public interface IEmailSender
{
    void Send(string to, string subject, string body);
}

public interface IClock
{
    DateOnly Today { get; }
}

public class ReminderService
{
    private readonly IRepository<Invoice> _invoices;
    private readonly IRepository<Customer> _customers;
    private readonly IEmailSender _sender;
    private readonly IClock _clock;

    public ReminderService(IRepository<Invoice> invoices, IRepository<Customer> customers, IEmailSender sender, IClock clock)
    {
        _invoices = invoices;
        _customers = customers;
        _sender = sender;
        _clock = clock;
    }

    /// <summary>Emails every customer with an unpaid invoice past its due date. Returns how many were sent.</summary>
    public int SendOverdueReminders()
    {
        DateOnly today = _clock.Today;
        int sent = 0;

        foreach (Invoice invoice in _invoices.GetAll().Where(i => !i.Paid && i.DueDate < today))
        {
            Customer? customer = _customers.Get(invoice.CustomerId);
            if (customer is null) continue;

            _sender.Send(
                customer.Email,
                $"Invoice {invoice.Id} is overdue",
                $"Hi {customer.Name}, invoice {invoice.Id} for {invoice.Amount:F2} was due on {invoice.DueDate:yyyy-MM-dd}.");
            sent++;
        }
        return sent;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now the tests:

// ===== ShopTests.cs =====
using Xunit;

namespace Shop.Tests;

public class RepositoryTests
{
    private readonly InMemoryRepository<Customer> _repository = new();

    [Fact]
    public void Add_ThenGet_ReturnsTheSameItem()
    {
        var customer = new Customer(1, "Asha", "asha@example.com");

        _repository.Add(customer);

        Assert.Equal(customer, _repository.Get(1));
    }

    [Fact]
    public void Add_DuplicateId_Throws()
    {
        _repository.Add(new Customer(1, "Asha", "asha@example.com"));

        var exception = Assert.Throws<InvalidOperationException>(
            () => _repository.Add(new Customer(1, "Other", "other@example.com")));

        Assert.Contains("already exists", exception.Message);
    }

    [Fact]
    public void Add_Null_Throws()
    {
        Assert.Throws<ArgumentNullException>(() => _repository.Add(null!));
    }

    [Theory]
    [InlineData(1)]
    [InlineData(42)]
    [InlineData(-5)]
    public void Get_UnknownId_ReturnsNull(int id)
    {
        Assert.Null(_repository.Get(id));
    }

    [Fact]
    public void Remove_ExistingItem_ReturnsTrueAndItemIsGone()
    {
        _repository.Add(new Customer(1, "Asha", "asha@example.com"));

        Assert.True(_repository.Remove(1));
        Assert.Null(_repository.Get(1));
    }

    [Fact]
    public void Remove_UnknownId_ReturnsFalse()
    {
        Assert.False(_repository.Remove(99));
    }

    [Fact]
    public void GetAll_OnEmptyRepository_ReturnsEmpty()
    {
        Assert.Empty(_repository.GetAll());
    }
}

public class ReminderServiceTests
{
    private static readonly DateOnly Today = new(2026, 11, 3);

    private readonly InMemoryRepository<Customer> _customers = new();
    private readonly InMemoryRepository<Invoice> _invoices = new();
    private readonly FakeEmailSender _sender = new();              // hand-written test double
    private readonly ReminderService _service;

    public ReminderServiceTests()
    {
        _customers.Add(new Customer(1, "Asha", "asha@example.com"));
        _service = new ReminderService(_invoices, _customers, _sender, new FixedClock(Today));
    }

    [Fact]
    public void OverdueUnpaidInvoice_SendsOneEmailToTheCustomer()
    {
        _invoices.Add(new Invoice(10, CustomerId: 1, Amount: 250m, DueDate: Today.AddDays(-5), Paid: false));

        int sent = _service.SendOverdueReminders();

        Assert.Equal(1, sent);
        var email = Assert.Single(_sender.Sent);
        Assert.Equal("asha@example.com", email.To);
        Assert.Equal("Invoice 10 is overdue", email.Subject);
    }

    [Fact]
    public void Email_MentionsTheCustomerNameAndTheAmount()
    {
        _invoices.Add(new Invoice(10, 1, 250m, Today.AddDays(-5), false));

        _service.SendOverdueReminders();

        Assert.Contains("Asha", _sender.Sent[0].Body);
        Assert.Contains("250.00", _sender.Sent[0].Body);
    }

    [Fact]
    public void PaidInvoice_IsIgnored()
    {
        _invoices.Add(new Invoice(10, 1, 250m, Today.AddDays(-5), Paid: true));

        Assert.Equal(0, _service.SendOverdueReminders());
        Assert.Empty(_sender.Sent);
    }

    [Theory]
    [InlineData(-30, 1)]     // long overdue
    [InlineData(-1, 1)]      // due yesterday
    [InlineData(0, 0)]       // due today: not overdue yet (the boundary)
    [InlineData(1, 0)]       // due tomorrow
    public void DueDateBoundary_DecidesWhetherAReminderIsSent(int daysFromToday, int expectedEmails)
    {
        _invoices.Add(new Invoice(10, 1, 100m, Today.AddDays(daysFromToday), false));

        Assert.Equal(expectedEmails, _service.SendOverdueReminders());
    }

    [Fact]
    public void InvoiceForUnknownCustomer_IsSkippedAndNotCounted()
    {
        _invoices.Add(new Invoice(10, CustomerId: 999, Amount: 100m, DueDate: Today.AddDays(-5), Paid: false));

        Assert.Equal(0, _service.SendOverdueReminders());
        Assert.Empty(_sender.Sent);
    }

    [Fact]
    public void TwoOverdueInvoices_SendTwoEmails()
    {
        _invoices.Add(new Invoice(10, 1, 100m, Today.AddDays(-5), false));
        _invoices.Add(new Invoice(11, 1, 200m, Today.AddDays(-2), false));

        Assert.Equal(2, _service.SendOverdueReminders());
        Assert.Equal(2, _sender.Sent.Count);
    }
}

// Test doubles: tiny hand-written fakes. A mocking library (Moq, NSubstitute) generates these for you.
public sealed class FakeEmailSender : IEmailSender
{
    public List<(string To, string Subject, string Body)> Sent { get; } = new();

    public void Send(string to, string subject, string body) => Sent.Add((to, subject, body));
}

public sealed class FixedClock : IClock
{
    public FixedClock(DateOnly today) => Today = today;

    public DateOnly Today { get; }
}
Enter fullscreen mode Exit fullscreen mode

All of them pass:

Passed! - Failed: 0, Passed: 18, Skipped: 0, Total: 18
Enter fullscreen mode Exit fullscreen mode

Why this is the best way to write it:

  1. The service can be tested at all because its dependencies are interfaces. ReminderService receives IEmailSender and IClock in its constructor. If it called new SmtpClient() and DateOnly.FromDateTime(DateTime.Now) itself, every test would send real mail and the result would change by the day.
  2. A fixed clock makes time-based logic deterministic. The tests say "today is 3 November", so "overdue" means the same thing on every machine, every day.
  3. The fake records what it was asked to do. FakeEmailSender.Sent lets a test assert on behaviour (who got an email, with what subject), which is exactly what the service is for. A mocking library does the same: Substitute.For<IEmailSender>() with sender.Received(1).Send(...) in NSubstitute, or new Mock<IEmailSender>() with Verify in Moq. Start with hand-written fakes; reach for a library when fakes become repetitive.
  4. Only the true boundaries are faked. The repositories are the real in-memory implementation, which is fast and honest. Faking everything makes tests pass while the real wiring is broken.
  5. Boundary conditions get their own theory. Due yesterday sends a reminder, due today does not, and the four rows pin that rule down. Most real bugs live exactly at the edges.
  6. Each test checks one behaviour, and the names read as a specification: PaidInvoice_IsIgnored, InvoiceForUnknownCustomer_IsSkippedAndNotCounted.
  7. Tests are independent. xUnit builds a new test class per test, so the constructor creates a fresh repository and service each time. No test depends on the order tests run in.
  8. The repository tests cover the failure paths too: duplicates, null, unknown ids and removing something that is not there. The happy path is the easy part.

Concept 13: Dependency injection concepts: interfaces and constructor injection

What it is. A class that creates its own collaborators (new SqlOrderStore(), DateTime.Now) is welded to them. Dependency injection (DI) reverses that: the class declares what it needs in its constructor, as interfaces, and whoever creates the class supplies them. The class no longer decides which database or which clock. This is the technique that makes the testing above possible, and ASP.NET Core is built around it.

The analogy: a plug and socket. A lamp does not wire itself to the power station. It has a plug of a standard shape, and any socket of that shape works: the wall, an extension lead, a battery pack. The plug is the constructor parameter, the standard shape is the interface, and the place where you decide which socket to use is the composition root.

Here is the class before: three hard-coded dependencies. It compiles and works, but you cannot test it without a real SQL Server and a real mail server, and its behaviour depends on what day it is.

var processor = new OrderProcessor();
processor.Process(new Order(1, "Asha", 200m));

public record Order(int Id, string Customer, decimal Total);

public class SqlOrderStore
{
    public SqlOrderStore(string connectionString) { }
    public void Save(Order order) => Console.WriteLine($"  [SQL Server] saved order {order.Id}");
}

public class SmtpEmailSender
{
    public void Send(string to, string message) => Console.WriteLine($"  [SMTP] to {to}: {message}");
}

public class OrderProcessor
{
    private readonly SqlOrderStore _store = new SqlOrderStore("Server=prod;Database=Shop");   // hard-coded
    private readonly SmtpEmailSender _email = new SmtpEmailSender();                           // hard-coded

    public void Process(Order order)
    {
        decimal total = order.Total;
        if (DateTime.Now.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday)                  // hard-coded clock
        {
            total *= 0.9m;
        }

        _store.Save(order with { Total = total });
        _email.Send(order.Customer, $"Your order total is {total:F2}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Practice question 13: refactor to constructor injection, by hand

Refactor the class above so that it uses constructor injection, with no DI framework. You will meet the framework itself on Day 6.

Solution

// The composition root: the ONE place that knows which concrete classes are used.
// In production it would read:
//   new OrderProcessor(new SystemClock(), new SqlOrderStore("Server=prod;Database=Shop"), new SmtpEmailSender());
// Here we wire in fixed and in-memory versions, which makes the result predictable.

Console.WriteLine("-- Saturday --");
Run(new DateTimeOffset(2026, 11, 7, 12, 0, 0, TimeSpan.Zero));

Console.WriteLine("-- Monday --");
Run(new DateTimeOffset(2026, 11, 9, 12, 0, 0, TimeSpan.Zero));

static void Run(DateTimeOffset now)
{
    var store = new InMemoryOrderStore();
    var email = new RecordingEmailSender();
    var processor = new OrderProcessor(new FixedClock(now), store, email);

    decimal charged = processor.Process(new Order(1, "Asha", 200m));

    Console.WriteLine($"  charged {charged:F2}");
    Console.WriteLine($"  orders saved: {store.Saved.Count}, stored total: {store.Saved[0].Total:F2}");
    Console.WriteLine($"  emails sent: {email.Sent.Count} -> {email.Sent[0]}");
}

public record Order(int Id, string Customer, decimal Total);

// The contracts the processor depends on
public interface IClock { DateTimeOffset Now { get; } }
public interface IOrderStore { void Save(Order order); }
public interface IEmailSender { void Send(string to, string message); }

public class OrderProcessor
{
    private readonly IClock _clock;
    private readonly IOrderStore _store;
    private readonly IEmailSender _email;

    public OrderProcessor(IClock clock, IOrderStore store, IEmailSender email)    // dependencies arrive here
    {
        _clock = clock ?? throw new ArgumentNullException(nameof(clock));
        _store = store ?? throw new ArgumentNullException(nameof(store));
        _email = email ?? throw new ArgumentNullException(nameof(email));
    }

    public decimal Process(Order order)
    {
        ArgumentNullException.ThrowIfNull(order);

        decimal total = IsWeekend(_clock.Now) ? order.Total * 0.9m : order.Total;

        _store.Save(order with { Total = total });
        _email.Send(order.Customer, $"Your order total is {total:F2}");
        return total;
    }

    private static bool IsWeekend(DateTimeOffset date) => date.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday;
}

// Real implementations (stubs here) and test-friendly ones live outside the processor
public sealed class SystemClock : IClock
{
    public DateTimeOffset Now => DateTimeOffset.Now;
}

public sealed class FixedClock : IClock
{
    public FixedClock(DateTimeOffset now) => Now = now;
    public DateTimeOffset Now { get; }
}

public sealed class InMemoryOrderStore : IOrderStore
{
    public List<Order> Saved { get; } = new();
    public void Save(Order order) => Saved.Add(order);
}

public sealed class RecordingEmailSender : IEmailSender
{
    public List<string> Sent { get; } = new();
    public void Send(string to, string message) => Sent.Add($"to {to}: {message}");
}
Enter fullscreen mode Exit fullscreen mode

Output:

-- Saturday --
  charged 180.00
  orders saved: 1, stored total: 180.00
  emails sent: 1 -> to Asha: Your order total is 180.00
-- Monday --
  charged 200.00
  orders saved: 1, stored total: 200.00
  emails sent: 1 -> to Asha: Your order total is 200.00
Enter fullscreen mode Exit fullscreen mode

Why this is the best way to write it:

  1. Each hard-coded new became an interface plus a constructor parameter. OrderProcessor now knows only what it needs (IClock, IOrderStore, IEmailSender), never which implementation. The business rule (weekend discount, save, notify) is all that is left inside it.
  2. The interfaces are small and named for the role, not the technology: IOrderStore, not ISqlOrderStore. A SQL version, a file version and an in-memory version can all satisfy it.
  3. The clock is a dependency too. DateTime.Now is a hidden input. Making it IClock is what lets the output above show a Saturday and a Monday on the same machine, on the same day.
  4. The composition root is the only place that knows the concrete types. Here that is the top of Program.cs. Everything else depends on abstractions. In a web app, this is Program.cs registering services.
  5. Constructor injection makes dependencies visible and required. You cannot create an OrderProcessor without supplying them, and the null checks fail fast if someone passes nothing. A hidden dependency inside a method is invisible from outside.
  6. The fakes in this program are the same shape as the ones in concept 12. FixedClock, InMemoryOrderStore and RecordingEmailSender are what you drop into a unit test. DI and testing are two halves of the same idea.
  7. Do not reach for a container first. Wiring by hand with new in one place is clear and enough for small programs. A container (Day 6) is just automation for exactly this wiring, and understanding the manual version first is what makes the container make sense.

Five classic mistakes

Each one follows the same pattern: what people write, why it hurts, what to write instead.

  1. Creating dependencies inside the class. new SmtpClient() and DateTime.Now in the middle of a method make the code impossible to test and impossible to change. Take an interface in the constructor instead, and wire concrete types in one place.
  2. Forgetting to dispose. A StreamWriter that is never disposed can lose its last buffered lines and keep the file locked. Put anything IDisposable in a using, and make your own disposable classes safe to dispose twice.
  3. Trusting incoming JSON. Deserializing without catching JsonException, forgetting the enum converter (so values are numbers) or assuming property names match exactly all fail in production. Wrap deserialization, share one configured JsonSerializerOptions, and validate the result.
  4. Tests that depend on the clock, the disk or the network. A test that passes on Monday and fails on Saturday is worse than no test. Inject a fixed clock, use in-memory implementations and temp files that clean up after themselves.
  5. Faking everything. If every collaborator is a fake, the test proves only that your fakes agree with each other. Fake the true boundaries (clock, email, network) and keep the rest real.

Key lessons

  • Dispose what you own: using for resources, sealed plus a simple Dispose by default, the full pattern only for inheritance
  • using is try/finally: disposal happens even when an exception is thrown, and nested usings unwind in reverse order
  • Configure System.Text.Json once, handle JsonException, and use a discriminator for polymorphism
  • A good unit test is Arrange, Act, Assert, with one behaviour and a name that says what it checks
  • Test the boundaries of a rule: due yesterday versus due today
  • Fake the boundaries (clock, email, network, disk); keep the rest real
  • Depend on interfaces, inject them through the constructor, and create concrete types in one composition root
  • Hand-wire first; a DI container is automation for exactly that wiring

Summary

Resource cleanup, JSON, testing and dependency injection are the habits that turn working code into maintainable code. Testing and DI are two halves of one idea: if a class asks for what it needs instead of creating it, you can prove it works. In Part 3 we put every mid-level concept from Days 3 and 4 into one project, an Expense Tracker with events, LINQ reports, pattern-matched categories, JSON persistence and 35 passing test cases.


More on these topics: C# posts

Top comments (0)