Dependencies by hand

A screen that asks DateTime.Today is untestable twice a year: the day the trial ends and the day it expires are the two dates a test needs, and the calendar will not produce them on request. The fix is not a framework. It is a constructor parameter.

A clock as a seam

A dependency is anything the class reads that it does not own: the clock, the file system, the database, the network, a random number. Each one that the class creates itself is a seam that cannot be opened. Replacing it with an interface and passing the implementation in gives the class a way to be tested and the program a way to choose:

internal interface IClock { DateOnly Today { get; } } internal sealed class SystemClock : IClock { public DateOnly Today => DateOnly.FromDateTime(DateTime.Today); } internal interface IAccountRepository { Account? Find(string id); } internal sealed record Account(string Id, string Name, DateOnly TrialEnds);

The interface is as small as the class needs, which is one property and one method here. A clock that also returned the time zone offset or a monotonic counter would be a clock designed for a library, not for this screen. DateOnly rather than DateTime is the same discipline: a trial ends on a day, not at 14:32:07.123.

Constructor injection

The service takes both dependencies as constructor parameters and stores them in readonly fields. It never creates one, never reads a static and never reaches for a service locator:

internal sealed class TrialService { private readonly IClock _clock; private readonly IAccountRepository _accounts; public TrialService(IClock clock, IAccountRepository accounts) { _clock = clock; _accounts = accounts; } public string BannerFor(string id) { var account = _accounts.Find(id); if (account is null) { return string.Empty; } var days = account.TrialEnds.DayNumber - _clock.Today.DayNumber; return days switch { < 0 => "Your trial has ended.", 0 => "Your trial ends today.", 1 => "Your trial ends tomorrow.", _ => $"Your trial ends in {days} days.", }; } }

DayNumber is the number of days since 0001-01-01, so the subtraction is exact and ignores time zones and daylight saving. A TimeSpan subtraction would make 23 hours look like zero days and 25 like one. The switch has four arms because the four cases read differently, which is a product decision and belongs in the service.

The parameterless constructor is deliberately absent. A default constructor that calls new SystemClock() is a seam that quietly closes; every caller then has to be changed when the clock is tested. One constructor that demands its dependencies is the whole of the pattern.

The composition root

Somebody has to create the real implementations, and in a desktop application that somebody is Main. It is the composition root: the one place allowed to know every concrete type, and the one place that changes when the application is wired differently. The form is a leaf that receives what it needs:

using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text.Json; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); IClock clock = new SystemClock(); IAccountRepository accounts = new JsonAccountRepository("accounts.json"); var service = new TrialService(clock, accounts); Application.Run(new AccountForm(service, "A-1")); } } internal interface IClock { DateOnly Today { get; } } internal sealed class SystemClock : IClock { public DateOnly Today => DateOnly.FromDateTime(DateTime.Today); } internal interface IAccountRepository { Account? Find(string id); } internal sealed record Account(string Id, string Name, DateOnly TrialEnds); internal sealed class JsonAccountRepository : IAccountRepository { private readonly string _path; public JsonAccountRepository(string path) => _path = path; public Account? Find(string id) { if (!File.Exists(_path)) { return null; } var accounts = JsonSerializer.Deserialize<List<Account>>(File.ReadAllText(_path)); return accounts?.Find(account => account.Id == id); } } internal sealed class TrialService { private readonly IClock _clock; private readonly IAccountRepository _accounts; public TrialService(IClock clock, IAccountRepository accounts) { _clock = clock; _accounts = accounts; } public string BannerFor(string id) { var account = _accounts.Find(id); if (account is null) { return string.Empty; } var days = account.TrialEnds.DayNumber - _clock.Today.DayNumber; return days switch { < 0 => "Your trial has ended.", 0 => "Your trial ends today.", 1 => "Your trial ends tomorrow.", _ => $"Your trial ends in {days} days.", }; } } internal sealed class AccountForm : Form { private readonly TrialService _service; private readonly string _accountId; public AccountForm(TrialService service, string accountId) { _service = service; _accountId = accountId; Text = "Account"; ClientSize = new Size(380, 120); var banner = new Label { Location = new Point(16, 20), AutoSize = true }; banner.Text = _service.BannerFor(_accountId); Controls.Add(banner); } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. Three lines of Main are the entire object graph of the application, which is why a desktop program needs no container: the graph is small, it is a tree, and it is created once. A container earns its place when discovery is needed, when lifetimes differ, or when a plugin decides what to construct; none of that is true of a login form.

The reading of accounts.json happens inside Find, on the UI thread, on every call. That is fine for a file of ten accounts and wrong for a network call: the fix is to make the repository asynchronous or to load once at startup, and because the form sees only the interface, the fix does not reach it.

Five dates that run

The service with a fake clock and a dictionary repository. The clock is a settable property, so the program asks the same account for its banner at five dates and the rule is visible at every boundary. It was built and run here:

using System; using System.Collections.Generic; Console.WriteLine("the trial banner at five dates"); var repository = new FakeAccountRepository(); repository.Add(new Account("A-1", "Ada", new DateOnly(2026, 12, 1))); repository.Add(new Account("B-2", "Grace", new DateOnly(2026, 11, 21))); var clock = new FakeClock(new DateOnly(2026, 11, 18)); var service = new TrialService(clock, repository); var days = new[] { new DateOnly(2026, 11, 18), new DateOnly(2026, 11, 25), new DateOnly(2026, 11, 30), new DateOnly(2026, 12, 1), new DateOnly(2026, 12, 2), }; foreach (var today in days) { clock.Today = today; Console.WriteLine($"{today:yyyy-MM-dd}: {service.BannerFor("A-1")}"); } clock.Today = new DateOnly(2026, 11, 21); Console.WriteLine($"B-2 today: {service.BannerFor("B-2")}"); Console.WriteLine($"unknown: '{service.BannerFor("X-9")}'"); internal interface IClock { DateOnly Today { get; } } internal interface IAccountRepository { Account? Find(string id); } internal sealed record Account(string Id, string Name, DateOnly TrialEnds); internal sealed class FakeClock : IClock { public FakeClock(DateOnly today) => Today = today; public DateOnly Today { get; set; } } internal sealed class FakeAccountRepository : IAccountRepository { private readonly Dictionary<string, Account> _accounts = new(); public void Add(Account account) => _accounts[account.Id] = account; public Account? Find(string id) => _accounts.TryGetValue(id, out var account) ? account : null; } internal sealed class TrialService { private readonly IClock _clock; private readonly IAccountRepository _accounts; public TrialService(IClock clock, IAccountRepository accounts) { _clock = clock; _accounts = accounts; } public string BannerFor(string id) { var account = _accounts.Find(id); if (account is null) { return string.Empty; } var days = account.TrialEnds.DayNumber - _clock.Today.DayNumber; return days switch { < 0 => "Your trial has ended.", 0 => "Your trial ends today.", 1 => "Your trial ends tomorrow.", _ => $"Your trial ends in {days} days.", }; } }

dotnet run

the trial banner at five dates
2026-11-18: Your trial ends in 13 days.
2026-11-25: Your trial ends in 6 days.
2026-11-30: Your trial ends tomorrow.
2026-12-01: Your trial ends today.
2026-12-02: Your trial has ended.
B-2 today: Your trial ends today.
unknown: ''

The output is the real run. Every branch of the service executed at its own date, the missing account produced an empty banner, and the fake clock made the five dates possible in one second. On a real machine the same test would have to wait months.

Rules of thumb

Exercises

  1. Add a IRandom seam for a discount draw and a fake that returns a fixed number.
  2. Change TrialService to take a third dependency, a formatter for the date, and pass the invariant culture in the console program.
  3. Explain why the form receives the service rather than constructing it, using the fake clock as the example.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is a seam in this lesson?

    Answer

    A dependency behind an interface that a test can replace

    The clock and the repository are the two seams of the screen.

  2. Why does TrialService subtract DayNumber values?

    Answer

    It counts whole days without time zones or daylight saving

    A TimeSpan subtraction makes 23 hours look like zero days.

  3. How is the real clock chosen?

    Answer

    In Main, the composition root, and passed to the service

    One place knows every concrete type.

  4. What does a parameterless constructor that creates the clock cost?

    Answer

    It closes the seam and every caller must change when the clock is tested

    The dependencies are hidden again, which is the problem injection solves.

  5. What did the run print for 2026-11-30?

    Answer

    Your trial ends tomorrow.

    One day before 2026-12-01 is the tomorrow arm.

  6. What did the run print for an unknown id?

    Answer

    An empty banner

    A missing account returns null and the service returns the empty string.

  7. Why is the fake clock a settable property?

    Answer

    The program moves the date to each case without recreating the service

    One service instance, five dates.

  8. What does the form know about the repository?

    Answer

    Nothing: it receives the service and calls BannerFor

    The form is a leaf of the object graph.

  9. When is a dependency container worth its weight?

    Answer

    When discovery, lifetimes or plugin selection are needed

    A desktop object graph is usually a small tree built once.

  10. Why not a settable static clock?

    Answer

    It leaks between tests and screens

    The constructor parameter gives the same control without the global.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.

Article author: Arthur Isaev

Banner image