# Dependency Injection: Hand Me What I Need

When a class builds its own database and reads the real clock, nothing outside it can change either one, so its rules can't be tested; dependency injection has the class ask for them in its constructor, and whoever makes it hands them in, which finishes the idea Pass 1 started with the bakery's settings.

Journeyman · OOP · Software Development · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Hand a class what it needs through its constructor, instead of letting it build or find it
- Spot the smells that point to dependency injection: a class that builds or reaches for what it uses, and tests that can't control it
- Choose between handing in an object and handing in a function, and say why

## Key takeaways

- The smell: new or a global inside a class for something it uses, and a test that can't control what the class sees.
- The cause: the class decides for itself which database and which clock, so nobody else can.
- The fix: the class asks for what it needs in its constructor, and whoever makes it hands those in. The app hands in the real ones; a test hands in its own.
- A dependency that answers one question, like "what day is it?", can be handed in as a function; one with several jobs, like storage, as an object.

**Before this:** *Meet the Library API* (version 1 of the checkout service), *Why Singleton Is Usually a Trap* (handing the bakery's settings in), and interfaces.

In Pass 1, the bakery's checkout stopped reaching for a shared settings object and was handed one instead, and its tests stopped failing each other. That was one object, made at the start of the app. The library's checkout service needs two things, a database and a clock, and the library's board has a question it can't answer yet. By the end of this lesson the service will be handed both, and the idea from Pass 1 will have its full name: *dependency injection*.

## The symptom: a test that can't say "20 days later"

The board wants proof: a book returned 20 days after it was borrowed (6 days late) costs $1.50. Here's the best test anyone can write against version 1. It uses the same simple `Report` the bakery's tests used, and the service from the last lesson, written short:

```csharp
// A test of the late fee. There's no way to tell the service "20 days later".
CheckoutService service = new CheckoutService();
Loan loan = service.Borrow("Maya", "The Lighthouse Keeper");
Report("Returned 20 days later", service.ReturnBook(loan.Id), 150);

void Report(string test, int actual, int expected)
{
    string Dollars(int cents) => $"${cents / 100}.{cents % 100:00}";
    Console.WriteLine(actual == expected
        ? $"{test}: late fee {Dollars(actual)}, passed"
        : $"{test}: late fee {Dollars(actual)}, expected {Dollars(expected)}, failed");
}

record Loan(int Id, string Member, string Title, DateOnly Due);

class LibraryDatabase
{
    private readonly List<Dictionary<string, string>> loans = new();
    public LibraryDatabase(string address) => Console.WriteLine($"Connecting to {address}...");
    public int Insert(Dictionary<string, string> row) { loans.Add(row); return loans.Count; }
    public Dictionary<string, string> Select(int id) => loans[id - 1];
}

class CheckoutService
{
    private readonly LibraryDatabase database = new LibraryDatabase("riverside-db");

    public Loan Borrow(string member, string title)
    {
        DateOnly due = DateOnly.FromDateTime(DateTime.Today).AddDays(14);
        int id = database.Insert(new() { ["member"] = member, ["title"] = title, ["due"] = due.ToString("yyyy-MM-dd") });
        return new Loan(id, member, title, due);
    }

    public int ReturnBook(int id)
    {
        DateOnly due = DateOnly.ParseExact(database.Select(id)["due"], "yyyy-MM-dd");
        int daysLate = Math.Max(0, DateOnly.FromDateTime(DateTime.Today).DayNumber - due.DayNumber);
        return Math.Min(daysLate * 25, 500);
    }
}
```

```text
Connecting to riverside-db...
Returned 20 days later: late fee $0.00, expected $1.50, failed
```

```java
record Loan(int id, String member, String title, LocalDate due) { }

class LibraryDatabase {
    private final List<Map<String, String>> loans = new ArrayList<>();
    LibraryDatabase(String address) { IO.println("Connecting to " + address + "..."); }
    int insert(Map<String, String> row) { loans.add(row); return loans.size(); }
    Map<String, String> select(int id) { return loans.get(id - 1); }
}

class CheckoutService {
    private final LibraryDatabase database = new LibraryDatabase("riverside-db");

    Loan borrow(String member, String title) {
        LocalDate due = LocalDate.now().plusDays(14);
        int id = database.insert(Map.of("member", member, "title", title, "due", due.toString()));
        return new Loan(id, member, title, due);
    }

    int returnBook(int id) {
        LocalDate due = LocalDate.parse(database.select(id).get("due"));
        long daysLate = Math.max(0, ChronoUnit.DAYS.between(due, LocalDate.now()));
        return (int) Math.min(daysLate * 25, 500);
    }
}

String dollars(int cents) { return String.format("$%d.%02d", cents / 100, cents % 100); }

void report(String test, int actual, int expected) {
    IO.println(actual == expected
        ? test + ": late fee " + dollars(actual) + ", passed"
        : test + ": late fee " + dollars(actual) + ", expected " + dollars(expected) + ", failed");
}

void main() {
    // A test of the late fee. There's no way to tell the service "20 days later".
    CheckoutService service = new CheckoutService();
    Loan loan = service.borrow("Maya", "The Lighthouse Keeper");
    report("Returned 20 days later", service.returnBook(loan.id()), 150);
}
```

```text
Connecting to riverside-db...
Returned 20 days later: late fee $0.00, expected $1.50, failed
```

```python
from dataclasses import dataclass
from datetime import date, timedelta


@dataclass
class Loan:
    id: int
    member: str
    title: str
    due: date


class LibraryDatabase:
    def __init__(self, address):
        print(f"Connecting to {address}...")
        self.loans = []

    def insert(self, row):
        self.loans.append(row)
        return len(self.loans)

    def select(self, id):
        return self.loans[id - 1]


class CheckoutService:
    def __init__(self):
        self.database = LibraryDatabase("riverside-db")

    def borrow(self, member, title):
        due = date.today() + timedelta(days=14)
        id = self.database.insert({"member": member, "title": title, "due": due.isoformat()})
        return Loan(id, member, title, due)

    def return_book(self, id):
        due = date.fromisoformat(self.database.select(id)["due"])
        days_late = max(0, (date.today() - due).days)
        return min(days_late * 25, 500)


def dollars(cents):
    return f"${cents // 100}.{cents % 100:02d}"


def report(test, actual, expected):
    if actual == expected:
        print(f"{test}: late fee {dollars(actual)}, passed")
    else:
        print(f"{test}: late fee {dollars(actual)}, expected {dollars(expected)}, failed")


# A test of the late fee. There's no way to tell the service "20 days later".
service = CheckoutService()
loan = service.borrow("Maya", "The Lighthouse Keeper")
report("Returned 20 days later", service.return_book(loan.id), 150)
```

```text
Connecting to riverside-db...
Returned 20 days later: late fee $0.00, expected $1.50, failed
```

```javascript
const DAY = 24 * 60 * 60 * 1000;
const addDays = (day, days) => new Date(Date.parse(day) + days * DAY).toISOString().slice(0, 10);
const daysBetween = (from, to) => Math.round((Date.parse(to) - Date.parse(from)) / DAY);

class LibraryDatabase {
  #loans = [];
  constructor(address) { console.log(`Connecting to ${address}...`); }
  insert(row) { this.#loans.push(row); return this.#loans.length; }
  select(id) { return this.#loans[id - 1]; }
}

class CheckoutService {
  #database = new LibraryDatabase("riverside-db");

  borrow(member, title) {
    const due = addDays(new Date().toISOString().slice(0, 10), 14);
    const id = this.#database.insert({ member, title, due });
    return { id, member, title, due };
  }

  returnBook(id) {
    const today = new Date().toISOString().slice(0, 10);
    const daysLate = Math.max(0, daysBetween(this.#database.select(id).due, today));
    return Math.min(daysLate * 25, 500);
  }
}

const dollars = (cents) => `$${(cents / 100).toFixed(2)}`;

function report(test, actual, expected) {
  console.log(actual === expected
    ? `${test}: late fee ${dollars(actual)}, passed`
    : `${test}: late fee ${dollars(actual)}, expected ${dollars(expected)}, failed`);
}

// A test of the late fee. There's no way to tell the service "20 days later".
const service = new CheckoutService();
const loan = service.borrow("Maya", "The Lighthouse Keeper");
report("Returned 20 days later", service.returnBook(loan.id), 150);
```

```text
Connecting to riverside-db...
Returned 20 days later: late fee $0.00, expected $1.50, failed
```

```typescript
const DAY = 24 * 60 * 60 * 1000;
const addDays = (day: string, days: number): string => new Date(Date.parse(day) + days * DAY).toISOString().slice(0, 10);
const daysBetween = (from: string, to: string): number => Math.round((Date.parse(to) - Date.parse(from)) / DAY);

interface Loan { id: number; member: string; title: string; due: string; }
type Row = Record<string, string>;

class LibraryDatabase {
  private loans: Row[] = [];
  constructor(address: string) { console.log(`Connecting to ${address}...`); }
  insert(row: Row): number { this.loans.push(row); return this.loans.length; }
  select(id: number): Row { return this.loans[id - 1]; }
}

class CheckoutService {
  private database = new LibraryDatabase("riverside-db");

  borrow(member: string, title: string): Loan {
    const due = addDays(new Date().toISOString().slice(0, 10), 14);
    const id = this.database.insert({ member, title, due });
    return { id, member, title, due };
  }

  returnBook(id: number): number {
    const today = new Date().toISOString().slice(0, 10);
    const daysLate = Math.max(0, daysBetween(this.database.select(id).due, today));
    return Math.min(daysLate * 25, 500);
  }
}

const dollars = (cents: number): string => `$${(cents / 100).toFixed(2)}`;

function report(test: string, actual: number, expected: number): void {
  console.log(actual === expected
    ? `${test}: late fee ${dollars(actual)}, passed`
    : `${test}: late fee ${dollars(actual)}, expected ${dollars(expected)}, failed`);
}

// A test of the late fee. There's no way to tell the service "20 days later".
const service = new CheckoutService();
const loan = service.borrow("Maya", "The Lighthouse Keeper");
report("Returned 20 days later", service.returnBook(loan.id), 150);
```

```text
Connecting to riverside-db...
Returned 20 days later: late fee $0.00, expected $1.50, failed
```

The rule is right, and so is the test's math. The test can't make 20 days pass, so the book comes back on the day it was borrowed and costs nothing. It also connected to the library's real database, `riverside-db`, to run a test.

- **The symptom:** `new` (or a global, such as the clock) inside a class for something it uses, and a test that can't control what that class sees.
- **The cause:** the service decides for itself which database and which clock. Nobody else gets a say, so nobody else can change them.

## What would you try?

**Change the computer's clock before the test.** It works once, on your computer. It changes the date for every program running there, and the next person to run the tests has to remember to do it too.

**Add a `daysLater` parameter to `returnBook`, for tests.** Now the real app's method has a setting that only tests use, and the database is still the real one.

**A shared place to look things up from, such as `Services.Get<Clock>()`, that a test can fill with its own clock first.** Closer, but the service still *reaches out* for its clock, so `new CheckoutService()` still hides what it needs, and two tests running at once fight over the one shared place. It's Pass 1's Singleton trap again, with more steps. (This look-up place has a name of its own, a *service locator*.)

What a good fix needs: the service shouldn't build or find its database and clock at all. Someone else should decide, and give them to it.

## The fix: ask for what you need

A restaurant's chef doesn't grow the vegetables or raise the chickens. The recipe lists what's needed, and the kitchen hands the chef those ingredients. On a training day, the teacher hands in practice ingredients, and the chef cooks the same recipe the same way.

![A restaurant kitchen: a chef at the counter reading a recipe card titled "Roast chicken" that lists "chicken, potatoes, rosemary", while a kitchen helper sets a basket holding exactly those three ingredients in front of the chef](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/41ea90800fdf4f3781363b112b6a9e0e.webp)

In code, **the class asks for what it needs in its constructor, and whoever makes the class hands those in**. The checkout service asks for "a database" and "something that tells the date". The start of the app hands in the real database and the real clock; a test hands in a test database and a clock set to whatever day it likes:

![Dependency injection's roles: the checkout service asks for a database and a clock. The start of the app makes the library database and the real clock and hands them in; a test makes a test database and a clock set to any day and hands those in. What's handed in is fenced](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/fd92d7b75bf94deb982437fea708c396.webp)

## How it got its name

A class's **dependencies** are the things it needs to do its job. Handing them in from outside, instead of letting the class build or find them, is called **dependency injection**: the start of the app *injects* the database and the clock, which only means it passes them in. Asking for them in the constructor, as here, is **constructor injection**, the most common kind. The name was coined in 2004, when teams building large Java apps kept landing on this fix and wrote it up. It isn't in the 1994 book, but every framework in this pass is built on it.

## The classic version: an interface and the constructor

The clock becomes a promise, `Clock`, with one job: say what day it is. `SystemClock` keeps it with the computer's clock, and a test's `FixedClock` keeps it with any day the test sets. The service asks for a database and a clock, and stores them:

```csharp
// A test: it makes its own clock and database, and hands them in.
FixedClock clock = new FixedClock(new DateOnly(2026, 3, 2));
CheckoutService service = new CheckoutService(new LibraryDatabase("test-db"), clock);
Loan loan = service.Borrow("Maya", "The Lighthouse Keeper");
clock.Today = clock.Today.AddDays(20);
Report("Returned 20 days later", service.ReturnBook(loan.Id), 150);

// The app: the start of the program makes the real parts and hands them in.
CheckoutService app = new CheckoutService(new LibraryDatabase("riverside-db"), new SystemClock());
Console.WriteLine($"App: loan {app.Borrow("Sam", "Rivers of Glass").Id} is due in 14 days");

void Report(string test, int actual, int expected)
{
    string Dollars(int cents) => $"${cents / 100}.{cents % 100:00}";
    Console.WriteLine(actual == expected
        ? $"{test}: late fee {Dollars(actual)}, passed"
        : $"{test}: late fee {Dollars(actual)}, expected {Dollars(expected)}, failed");
}

record Loan(int Id, string Member, string Title, DateOnly Due);

interface IClock { DateOnly Today { get; } }

class SystemClock : IClock { public DateOnly Today => DateOnly.FromDateTime(DateTime.Today); }

class FixedClock : IClock
{
    public FixedClock(DateOnly today) => Today = today;
    public DateOnly Today { get; set; }
}

class LibraryDatabase
{
    private readonly List<Dictionary<string, string>> loans = new();
    public LibraryDatabase(string address) => Console.WriteLine($"Connecting to {address}...");
    public int Insert(Dictionary<string, string> row) { loans.Add(row); return loans.Count; }
    public Dictionary<string, string> Select(int id) => loans[id - 1];
}

class CheckoutService
{
    private readonly LibraryDatabase database;
    private readonly IClock clock;

    // It asks for what it needs, and stores what it's handed.
    public CheckoutService(LibraryDatabase database, IClock clock)
    {
        this.database = database;
        this.clock = clock;
    }

    public Loan Borrow(string member, string title)
    {
        DateOnly due = clock.Today.AddDays(14);
        int id = database.Insert(new() { ["member"] = member, ["title"] = title, ["due"] = due.ToString("yyyy-MM-dd") });
        return new Loan(id, member, title, due);
    }

    public int ReturnBook(int id)
    {
        DateOnly due = DateOnly.ParseExact(database.Select(id)["due"], "yyyy-MM-dd");
        int daysLate = Math.Max(0, clock.Today.DayNumber - due.DayNumber);
        return Math.Min(daysLate * 25, 500);
    }
}
```

```text
Connecting to test-db...
Returned 20 days later: late fee $1.50, passed
Connecting to riverside-db...
App: loan 1 is due in 14 days
```

```java
record Loan(int id, String member, String title, LocalDate due) { }

interface Clock { LocalDate today(); }

class SystemClock implements Clock { public LocalDate today() { return LocalDate.now(); } }

class FixedClock implements Clock {
    LocalDate day;
    FixedClock(LocalDate day) { this.day = day; }
    public LocalDate today() { return day; }
}

class LibraryDatabase {
    private final List<Map<String, String>> loans = new ArrayList<>();
    LibraryDatabase(String address) { IO.println("Connecting to " + address + "..."); }
    int insert(Map<String, String> row) { loans.add(row); return loans.size(); }
    Map<String, String> select(int id) { return loans.get(id - 1); }
}

class CheckoutService {
    private final LibraryDatabase database;
    private final Clock clock;

    // It asks for what it needs, and stores what it's handed.
    CheckoutService(LibraryDatabase database, Clock clock) {
        this.database = database;
        this.clock = clock;
    }

    Loan borrow(String member, String title) {
        LocalDate due = clock.today().plusDays(14);
        int id = database.insert(Map.of("member", member, "title", title, "due", due.toString()));
        return new Loan(id, member, title, due);
    }

    int returnBook(int id) {
        LocalDate due = LocalDate.parse(database.select(id).get("due"));
        long daysLate = Math.max(0, ChronoUnit.DAYS.between(due, clock.today()));
        return (int) Math.min(daysLate * 25, 500);
    }
}

String dollars(int cents) { return String.format("$%d.%02d", cents / 100, cents % 100); }

void report(String test, int actual, int expected) {
    IO.println(actual == expected
        ? test + ": late fee " + dollars(actual) + ", passed"
        : test + ": late fee " + dollars(actual) + ", expected " + dollars(expected) + ", failed");
}

void main() {
    // A test: it makes its own clock and database, and hands them in.
    FixedClock clock = new FixedClock(LocalDate.of(2026, 3, 2));
    CheckoutService service = new CheckoutService(new LibraryDatabase("test-db"), clock);
    Loan loan = service.borrow("Maya", "The Lighthouse Keeper");
    clock.day = clock.day.plusDays(20);
    report("Returned 20 days later", service.returnBook(loan.id()), 150);

    // The app: the start of the program makes the real parts and hands them in.
    CheckoutService app = new CheckoutService(new LibraryDatabase("riverside-db"), new SystemClock());
    IO.println("App: loan " + app.borrow("Sam", "Rivers of Glass").id() + " is due in 14 days");
}
```

```text
Connecting to test-db...
Returned 20 days later: late fee $1.50, passed
Connecting to riverside-db...
App: loan 1 is due in 14 days
```

```python
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import date, timedelta


@dataclass
class Loan:
    id: int
    member: str
    title: str
    due: date


class Clock(ABC):
    @abstractmethod
    def today(self): ...


class SystemClock(Clock):
    def today(self):
        return date.today()


class FixedClock(Clock):
    def __init__(self, day):
        self.day = day

    def today(self):
        return self.day


class LibraryDatabase:
    def __init__(self, address):
        print(f"Connecting to {address}...")
        self.loans = []

    def insert(self, row):
        self.loans.append(row)
        return len(self.loans)

    def select(self, id):
        return self.loans[id - 1]


class CheckoutService:
    def __init__(self, database, clock):
        # It asks for what it needs, and stores what it's handed.
        self.database = database
        self.clock = clock

    def borrow(self, member, title):
        due = self.clock.today() + timedelta(days=14)
        id = self.database.insert({"member": member, "title": title, "due": due.isoformat()})
        return Loan(id, member, title, due)

    def return_book(self, id):
        due = date.fromisoformat(self.database.select(id)["due"])
        days_late = max(0, (self.clock.today() - due).days)
        return min(days_late * 25, 500)


def dollars(cents):
    return f"${cents // 100}.{cents % 100:02d}"


def report(test, actual, expected):
    if actual == expected:
        print(f"{test}: late fee {dollars(actual)}, passed")
    else:
        print(f"{test}: late fee {dollars(actual)}, expected {dollars(expected)}, failed")


# A test: it makes its own clock and database, and hands them in.
clock = FixedClock(date(2026, 3, 2))
service = CheckoutService(LibraryDatabase("test-db"), clock)
loan = service.borrow("Maya", "The Lighthouse Keeper")
clock.day += timedelta(days=20)
report("Returned 20 days later", service.return_book(loan.id), 150)

# The app: the start of the program makes the real parts and hands them in.
app = CheckoutService(LibraryDatabase("riverside-db"), SystemClock())
print(f"App: loan {app.borrow('Sam', 'Rivers of Glass').id} is due in 14 days")
```

```text
Connecting to test-db...
Returned 20 days later: late fee $1.50, passed
Connecting to riverside-db...
App: loan 1 is due in 14 days
```

```javascript
const DAY = 24 * 60 * 60 * 1000;
const addDays = (day, days) => new Date(Date.parse(day) + days * DAY).toISOString().slice(0, 10);
const daysBetween = (from, to) => Math.round((Date.parse(to) - Date.parse(from)) / DAY);

// Two clocks that keep the same promise: today() gives a "YYYY-MM-DD" day.
class SystemClock { today() { return new Date().toISOString().slice(0, 10); } }

class FixedClock {
  constructor(day) { this.day = day; }
  today() { return this.day; }
}

class LibraryDatabase {
  #loans = [];
  constructor(address) { console.log(`Connecting to ${address}...`); }
  insert(row) { this.#loans.push(row); return this.#loans.length; }
  select(id) { return this.#loans[id - 1]; }
}

class CheckoutService {
  #database;
  #clock;

  // It asks for what it needs, and stores what it's handed.
  constructor(database, clock) {
    this.#database = database;
    this.#clock = clock;
  }

  borrow(member, title) {
    const due = addDays(this.#clock.today(), 14);
    const id = this.#database.insert({ member, title, due });
    return { id, member, title, due };
  }

  returnBook(id) {
    const daysLate = Math.max(0, daysBetween(this.#database.select(id).due, this.#clock.today()));
    return Math.min(daysLate * 25, 500);
  }
}

const dollars = (cents) => `$${(cents / 100).toFixed(2)}`;

function report(test, actual, expected) {
  console.log(actual === expected
    ? `${test}: late fee ${dollars(actual)}, passed`
    : `${test}: late fee ${dollars(actual)}, expected ${dollars(expected)}, failed`);
}

// A test: it makes its own clock and database, and hands them in.
const clock = new FixedClock("2026-03-02");
const service = new CheckoutService(new LibraryDatabase("test-db"), clock);
const loan = service.borrow("Maya", "The Lighthouse Keeper");
clock.day = addDays(clock.day, 20);
report("Returned 20 days later", service.returnBook(loan.id), 150);

// The app: the start of the program makes the real parts and hands them in.
const app = new CheckoutService(new LibraryDatabase("riverside-db"), new SystemClock());
console.log(`App: loan ${app.borrow("Sam", "Rivers of Glass").id} is due in 14 days`);
```

```text
Connecting to test-db...
Returned 20 days later: late fee $1.50, passed
Connecting to riverside-db...
App: loan 1 is due in 14 days
```

```typescript
const DAY = 24 * 60 * 60 * 1000;
const addDays = (day: string, days: number): string => new Date(Date.parse(day) + days * DAY).toISOString().slice(0, 10);
const daysBetween = (from: string, to: string): number => Math.round((Date.parse(to) - Date.parse(from)) / DAY);

interface Loan { id: number; member: string; title: string; due: string; }
type Row = Record<string, string>;

interface Clock { today(): string; }

class SystemClock implements Clock { today(): string { return new Date().toISOString().slice(0, 10); } }

class FixedClock implements Clock {
  day: string;
  constructor(day: string) { this.day = day; }
  today(): string { return this.day; }
}

class LibraryDatabase {
  private loans: Row[] = [];
  constructor(address: string) { console.log(`Connecting to ${address}...`); }
  insert(row: Row): number { this.loans.push(row); return this.loans.length; }
  select(id: number): Row { return this.loans[id - 1]; }
}

class CheckoutService {
  private readonly database: LibraryDatabase;
  private readonly clock: Clock;

  // It asks for what it needs, and stores what it's handed.
  constructor(database: LibraryDatabase, clock: Clock) {
    this.database = database;
    this.clock = clock;
  }

  borrow(member: string, title: string): Loan {
    const due = addDays(this.clock.today(), 14);
    const id = this.database.insert({ member, title, due });
    return { id, member, title, due };
  }

  returnBook(id: number): number {
    const daysLate = Math.max(0, daysBetween(this.database.select(id).due, this.clock.today()));
    return Math.min(daysLate * 25, 500);
  }
}

const dollars = (cents: number): string => `$${(cents / 100).toFixed(2)}`;

function report(test: string, actual: number, expected: number): void {
  console.log(actual === expected
    ? `${test}: late fee ${dollars(actual)}, passed`
    : `${test}: late fee ${dollars(actual)}, expected ${dollars(expected)}, failed`);
}

// A test: it makes its own clock and database, and hands them in.
const clock = new FixedClock("2026-03-02");
const service = new CheckoutService(new LibraryDatabase("test-db"), clock);
const loan = service.borrow("Maya", "The Lighthouse Keeper");
clock.day = addDays(clock.day, 20);
report("Returned 20 days later", service.returnBook(loan.id), 150);

// The app: the start of the program makes the real parts and hands them in.
const app = new CheckoutService(new LibraryDatabase("riverside-db"), new SystemClock());
console.log(`App: loan ${app.borrow("Sam", "Rivers of Glass").id} is due in 14 days`);
```

```text
Connecting to test-db...
Returned 20 days later: late fee $1.50, passed
Connecting to riverside-db...
App: loan 1 is due in 14 days
```

The test passes, because it decides what day it is. The app still uses the real clock and the real database, made in one place at the start. And `new CheckoutService(database, clock)` now says out loud what the service needs: no hidden dependencies.

The test still connects to a database, `test-db`, though. The service asks for that one exact class, `LibraryDatabase`. *Repository: Ask for the Book, Not the Shelf* fixes that, two lessons from now.

## The modern version: hand in a function

Look at what the clock does: it answers one question, "what day is it?". In Pass 1, a weekly deal that answered one question ("how much off?") was handed in as a function, and nothing more was needed. A clock is the same. The service asks for a *function* that gives today's date:

```csharp
// The test's day lives in a variable; the function it hands in reads it.
DateOnly day = new DateOnly(2026, 3, 2);
CheckoutService service = new CheckoutService(new LibraryDatabase("test-db"), () => day);
Loan loan = service.Borrow("Maya", "The Lighthouse Keeper");
day = day.AddDays(20);
Report("Returned 20 days later", service.ReturnBook(loan.Id), 150);

CheckoutService app = new CheckoutService(new LibraryDatabase("riverside-db"), () => DateOnly.FromDateTime(DateTime.Today));
Console.WriteLine($"App: loan {app.Borrow("Sam", "Rivers of Glass").Id} is due in 14 days");

void Report(string test, int actual, int expected)
{
    string Dollars(int cents) => $"${cents / 100}.{cents % 100:00}";
    Console.WriteLine(actual == expected
        ? $"{test}: late fee {Dollars(actual)}, passed"
        : $"{test}: late fee {Dollars(actual)}, expected {Dollars(expected)}, failed");
}

record Loan(int Id, string Member, string Title, DateOnly Due);

class LibraryDatabase
{
    private readonly List<Dictionary<string, string>> loans = new();
    public LibraryDatabase(string address) => Console.WriteLine($"Connecting to {address}...");
    public int Insert(Dictionary<string, string> row) { loans.Add(row); return loans.Count; }
    public Dictionary<string, string> Select(int id) => loans[id - 1];
}

class CheckoutService
{
    private readonly LibraryDatabase database;
    private readonly Func<DateOnly> today;

    public CheckoutService(LibraryDatabase database, Func<DateOnly> today)
    {
        this.database = database;
        this.today = today;
    }

    public Loan Borrow(string member, string title)
    {
        DateOnly due = today().AddDays(14);
        int id = database.Insert(new() { ["member"] = member, ["title"] = title, ["due"] = due.ToString("yyyy-MM-dd") });
        return new Loan(id, member, title, due);
    }

    public int ReturnBook(int id)
    {
        DateOnly due = DateOnly.ParseExact(database.Select(id)["due"], "yyyy-MM-dd");
        int daysLate = Math.Max(0, today().DayNumber - due.DayNumber);
        return Math.Min(daysLate * 25, 500);
    }
}
```

```text
Connecting to test-db...
Returned 20 days later: late fee $1.50, passed
Connecting to riverside-db...
App: loan 1 is due in 14 days
```

```java
record Loan(int id, String member, String title, LocalDate due) { }

class LibraryDatabase {
    private final List<Map<String, String>> loans = new ArrayList<>();
    LibraryDatabase(String address) { IO.println("Connecting to " + address + "..."); }
    int insert(Map<String, String> row) { loans.add(row); return loans.size(); }
    Map<String, String> select(int id) { return loans.get(id - 1); }
}

class CheckoutService {
    private final LibraryDatabase database;
    private final Supplier<LocalDate> today;

    CheckoutService(LibraryDatabase database, Supplier<LocalDate> today) {
        this.database = database;
        this.today = today;
    }

    Loan borrow(String member, String title) {
        LocalDate due = today.get().plusDays(14);
        int id = database.insert(Map.of("member", member, "title", title, "due", due.toString()));
        return new Loan(id, member, title, due);
    }

    int returnBook(int id) {
        LocalDate due = LocalDate.parse(database.select(id).get("due"));
        long daysLate = Math.max(0, ChronoUnit.DAYS.between(due, today.get()));
        return (int) Math.min(daysLate * 25, 500);
    }
}

String dollars(int cents) { return String.format("$%d.%02d", cents / 100, cents % 100); }

void report(String test, int actual, int expected) {
    IO.println(actual == expected
        ? test + ": late fee " + dollars(actual) + ", passed"
        : test + ": late fee " + dollars(actual) + ", expected " + dollars(expected) + ", failed");
}

void main() {
    // The test's day lives in a one-item array, so the function it hands in can see it change.
    LocalDate[] day = { LocalDate.of(2026, 3, 2) };
    CheckoutService service = new CheckoutService(new LibraryDatabase("test-db"), () -> day[0]);
    Loan loan = service.borrow("Maya", "The Lighthouse Keeper");
    day[0] = day[0].plusDays(20);
    report("Returned 20 days later", service.returnBook(loan.id()), 150);

    CheckoutService app = new CheckoutService(new LibraryDatabase("riverside-db"), LocalDate::now);
    IO.println("App: loan " + app.borrow("Sam", "Rivers of Glass").id() + " is due in 14 days");
}
```

```text
Connecting to test-db...
Returned 20 days later: late fee $1.50, passed
Connecting to riverside-db...
App: loan 1 is due in 14 days
```

```python
from dataclasses import dataclass
from datetime import date, timedelta


@dataclass
class Loan:
    id: int
    member: str
    title: str
    due: date


class LibraryDatabase:
    def __init__(self, address):
        print(f"Connecting to {address}...")
        self.loans = []

    def insert(self, row):
        self.loans.append(row)
        return len(self.loans)

    def select(self, id):
        return self.loans[id - 1]


class CheckoutService:
    def __init__(self, database, today):
        self.database = database
        self.today = today

    def borrow(self, member, title):
        due = self.today() + timedelta(days=14)
        id = self.database.insert({"member": member, "title": title, "due": due.isoformat()})
        return Loan(id, member, title, due)

    def return_book(self, id):
        due = date.fromisoformat(self.database.select(id)["due"])
        days_late = max(0, (self.today() - due).days)
        return min(days_late * 25, 500)


def dollars(cents):
    return f"${cents // 100}.{cents % 100:02d}"


def report(test, actual, expected):
    if actual == expected:
        print(f"{test}: late fee {dollars(actual)}, passed")
    else:
        print(f"{test}: late fee {dollars(actual)}, expected {dollars(expected)}, failed")


# The test's day lives in a variable; the function it hands in reads it.
day = date(2026, 3, 2)
service = CheckoutService(LibraryDatabase("test-db"), lambda: day)
loan = service.borrow("Maya", "The Lighthouse Keeper")
day += timedelta(days=20)
report("Returned 20 days later", service.return_book(loan.id), 150)

app = CheckoutService(LibraryDatabase("riverside-db"), date.today)
print(f"App: loan {app.borrow('Sam', 'Rivers of Glass').id} is due in 14 days")
```

```text
Connecting to test-db...
Returned 20 days later: late fee $1.50, passed
Connecting to riverside-db...
App: loan 1 is due in 14 days
```

```javascript
const DAY = 24 * 60 * 60 * 1000;
const addDays = (day, days) => new Date(Date.parse(day) + days * DAY).toISOString().slice(0, 10);
const daysBetween = (from, to) => Math.round((Date.parse(to) - Date.parse(from)) / DAY);

class LibraryDatabase {
  #loans = [];
  constructor(address) { console.log(`Connecting to ${address}...`); }
  insert(row) { this.#loans.push(row); return this.#loans.length; }
  select(id) { return this.#loans[id - 1]; }
}

class CheckoutService {
  #database;
  #today;

  constructor(database, today) {
    this.#database = database;
    this.#today = today;
  }

  borrow(member, title) {
    const due = addDays(this.#today(), 14);
    const id = this.#database.insert({ member, title, due });
    return { id, member, title, due };
  }

  returnBook(id) {
    const daysLate = Math.max(0, daysBetween(this.#database.select(id).due, this.#today()));
    return Math.min(daysLate * 25, 500);
  }
}

const dollars = (cents) => `$${(cents / 100).toFixed(2)}`;

function report(test, actual, expected) {
  console.log(actual === expected
    ? `${test}: late fee ${dollars(actual)}, passed`
    : `${test}: late fee ${dollars(actual)}, expected ${dollars(expected)}, failed`);
}

// The test's day lives in a variable; the function it hands in reads it.
let day = "2026-03-02";
const service = new CheckoutService(new LibraryDatabase("test-db"), () => day);
const loan = service.borrow("Maya", "The Lighthouse Keeper");
day = addDays(day, 20);
report("Returned 20 days later", service.returnBook(loan.id), 150);

const app = new CheckoutService(new LibraryDatabase("riverside-db"), () => new Date().toISOString().slice(0, 10));
console.log(`App: loan ${app.borrow("Sam", "Rivers of Glass").id} is due in 14 days`);
```

```text
Connecting to test-db...
Returned 20 days later: late fee $1.50, passed
Connecting to riverside-db...
App: loan 1 is due in 14 days
```

```typescript
const DAY = 24 * 60 * 60 * 1000;
const addDays = (day: string, days: number): string => new Date(Date.parse(day) + days * DAY).toISOString().slice(0, 10);
const daysBetween = (from: string, to: string): number => Math.round((Date.parse(to) - Date.parse(from)) / DAY);

interface Loan { id: number; member: string; title: string; due: string; }
type Row = Record<string, string>;

class LibraryDatabase {
  private loans: Row[] = [];
  constructor(address: string) { console.log(`Connecting to ${address}...`); }
  insert(row: Row): number { this.loans.push(row); return this.loans.length; }
  select(id: number): Row { return this.loans[id - 1]; }
}

class CheckoutService {
  private readonly database: LibraryDatabase;
  private readonly today: () => string;

  constructor(database: LibraryDatabase, today: () => string) {
    this.database = database;
    this.today = today;
  }

  borrow(member: string, title: string): Loan {
    const due = addDays(this.today(), 14);
    const id = this.database.insert({ member, title, due });
    return { id, member, title, due };
  }

  returnBook(id: number): number {
    const daysLate = Math.max(0, daysBetween(this.database.select(id).due, this.today()));
    return Math.min(daysLate * 25, 500);
  }
}

const dollars = (cents: number): string => `$${(cents / 100).toFixed(2)}`;

function report(test: string, actual: number, expected: number): void {
  console.log(actual === expected
    ? `${test}: late fee ${dollars(actual)}, passed`
    : `${test}: late fee ${dollars(actual)}, expected ${dollars(expected)}, failed`);
}

// The test's day lives in a variable; the function it hands in reads it.
let day = "2026-03-02";
const service = new CheckoutService(new LibraryDatabase("test-db"), () => day);
const loan = service.borrow("Maya", "The Lighthouse Keeper");
day = addDays(day, 20);
report("Returned 20 days later", service.returnBook(loan.id), 150);

const app = new CheckoutService(new LibraryDatabase("riverside-db"), () => new Date().toISOString().slice(0, 10));
console.log(`App: loan ${app.borrow("Sam", "Rivers of Glass").id} is due in 14 days`);
```

```text
Connecting to test-db...
Returned 20 days later: late fee $1.50, passed
Connecting to riverside-db...
App: loan 1 is due in 14 days
```

**Where the languages differ.** C# and Python closures (a function that reads a variable from around it) see the variable's latest value, and so do JavaScript's and TypeScript's. A Java lambda may only read variables that never change, so the Java test keeps its day in a one-item array and changes what's inside. In a real Java app you'd use the built-in `java.time.Clock`, which exists for exactly this; .NET has `TimeProvider` for the same job.

**Function or object?** The same rule as Pass 1's weekly deal and Pass 2's carrier rates: a dependency that answers one question can be a function. The database has several jobs (save a loan, find one), so it stays an object.

## Where you've already used it

- **Pass 1:** `new Checkout(settings)` and the facade handed its four parts were dependency injection by hand, before the name.
- **Every function you've handed in:** a weekly deal, a listener, a sort's compare rule. Each is a dependency the caller chose.
- **Every framework in this pass.** Here is the checkout service as each language's best-known web framework writes it. The class still asks for what it needs; the framework does the handing in (the next lesson shows how).

**What this looks like in a framework.** These aren't run here: each needs its framework's project around it. Versions checked on 2026-11-01.

```csharp
// ASP.NET Core 10: the class asks for what it needs in its constructor, and the
// framework hands it in. TimeProvider is .NET's own clock; a test hands in a fake one.
public class CheckoutService(LibraryDatabase database, TimeProvider clock)
{
    public Loan Borrow(string member, string title)
    {
        DateOnly due = DateOnly.FromDateTime(clock.GetLocalNow().DateTime).AddDays(14);
        int id = database.Insert(new() { ["member"] = member, ["title"] = title, ["due"] = due.ToString("yyyy-MM-dd") });
        return new Loan(id, member, title, due);
    }
}
```

```java
// Spring Boot 4.1: @Service tells Spring to make one CheckoutService and hand its
// constructor what it asks for. java.time.Clock is Java's own clock; a test hands in Clock.fixed(...).
import java.time.Clock;
import java.time.LocalDate;
import java.util.Map;
import org.springframework.stereotype.Service;

@Service
public class CheckoutService {
    private final LibraryDatabase database;
    private final Clock clock;

    public CheckoutService(LibraryDatabase database, Clock clock) {
        this.database = database;
        this.clock = clock;
    }

    public Loan borrow(String member, String title) {
        LocalDate due = LocalDate.now(clock).plusDays(14);
        int id = database.insert(Map.of("member", member, "title", title, "due", due.toString()));
        return new Loan(id, member, title, due);
    }
}
```

```python
# FastAPI 0.162: Depends(...) names what an endpoint needs; FastAPI calls that
# function for each request and hands in what it returns.
from datetime import date

from fastapi import Depends, FastAPI

from library import CheckoutService, LibraryDatabase

app = FastAPI()
database = LibraryDatabase("riverside-db")


def get_checkout() -> CheckoutService:
    return CheckoutService(database, date.today)


@app.post("/loans")
def borrow(member: str, title: str, checkout: CheckoutService = Depends(get_checkout)):
    loan = checkout.borrow(member, title)
    return {"id": loan.id, "due": loan.due.isoformat()}
```

```javascript
// Express 5.3: no container. The start file makes the parts and hands them in by hand,
// exactly as this lesson's code does.
import express from "express";
import { CheckoutService, LibraryDatabase } from "./library.js";

const checkout = new CheckoutService(new LibraryDatabase("riverside-db"), () => new Date().toISOString().slice(0, 10));

const app = express();
app.use(express.json());
app.post("/loans", (req, res) => {
  const loan = checkout.borrow(req.body.member, req.body.title);
  res.status(201).json(loan);
});
app.listen(3000);
```

```typescript
// NestJS 12.3: @Injectable() marks a class Nest can make; its constructor says what to hand in.
// The clock is an abstract class, not an interface, so Nest can still find it when the program runs.
import { Injectable } from "@nestjs/common";
import { addDays, Clock, LibraryDatabase, type Loan } from "./library";

@Injectable()
export class CheckoutService {
  constructor(
    private readonly database: LibraryDatabase,
    private readonly clock: Clock,
  ) {}

  borrow(member: string, title: string): Loan {
    const due = addDays(this.clock.today(), 14);
    const id = this.database.insert({ member, title, due });
    return { id, member, title, due };
  }
}
```

Angular, a framework for the screens of a web app, works the same way: a class marked `@Injectable()` is handed what it asks for, through its constructor or Angular's `inject()` function.

## When not to use it

- **For plain values and plain data.** A loan doesn't need its title injected; it's plain data. The 14 days and the $0.25 are rules, not dependencies.
- **For small helpers that can't fail and never vary,** such as `Math.max` or a date's own `AddDays`. There's nothing to swap.
- **When a constructor asks for eight things.** That's a class doing too many jobs. Injection makes it visible; splitting the class fixes it.

The cost: someone has to make the parts and hand them in, and to know which clock the service uses, you look at where it was made, not inside it. The next lesson gives that job one home.

**How often you'll meet it:** every day (our estimate: every framework in this pass is built around it).

## Check yourself

2 questions to try on the lesson page.

## So what

A class that asks for what it needs can be handed the real thing in the app and a stand-in in a test, and it never has to know the difference. That one change is how Pass 1's settings object should always have been made, and it's the idea every framework in this pass is built on.

## Key terms

- [Dependency Injection](https://www.ask-codey.com/glossary/dependency-injection)
- [Constructor Injection](https://www.ask-codey.com/glossary/constructor-injection-oop)
- [Hidden Dependency](https://www.ask-codey.com/glossary/hidden-dependency)
- [Singleton Pattern](https://www.ask-codey.com/glossary/singleton-pattern)

## Cheat sheets

- [Dependency Injection: Hand Me What I Need](https://www.ask-codey.com/cheat-sheets/dp-dependency-injection-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-dependency-injection
