# Containers: Who Does the Handing Out

Once every class asks for what it needs, someone has to make the parts and hand them out; doing it in one place at the start of the app (the composition root) keeps it from being copied everywhere, and a container automates that place, with lifetimes that say whether a part is made once for the app, once per request, or new every time.

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

By Gregor Dzierzon

## After this lesson you can

- Wire an app in one composition root that makes each part once and hands it to whatever needs it
- Explain a container's lifetimes (one for the app, one per request, a new one every time) and pick one for a part
- Decide whether an app needs a container or whether wiring by hand is enough, and say why

## Key takeaways

- When every part of an app builds its own services, the wiring is copied everywhere and the app opens a database connection for each copy.
- A composition root is the one place, at the start of the app, that makes the parts and hands them out.
- A container is a composition root with a machine in it: you tell it how to make each part once, and it makes them, in the right order, when asked.
- Lifetimes say how long a part lives: one for the whole app, one per request, or a new one every time it's asked for.
- ASP.NET Core, Spring and Angular are built around a container; Python and JavaScript apps often wire by hand in one start file, which is the same pattern without the machine.

**Before this:** *Dependency Injection: Hand Me What I Need*.

The checkout service now asks for its database and its clock, and doesn't build them. That moved the building somewhere else. In a small program, "somewhere else" was three lines at the top. The library's API has grown, though, and the building has started turning up everywhere. This lesson gives it one home, and then meets the machine every big framework puts in that home: a **container**.

## The symptom: everyone builds their own

The API now has three parts that need a checkout or reminder service: the website's handler, the self-checkout kiosk's handler, and a nightly job that emails reminders about books due soon. Each was written by someone different, and each builds what it needs. The services are written short here; only the wiring matters:

```csharp
Website();
Kiosk();
NightlyReminders();

// Each part of the app builds its own services, and everything inside them.
void Website()
{
    CheckoutService checkout = new CheckoutService(new LibraryDatabase("riverside-db"), new SystemClock());
    Console.WriteLine("Website: " + checkout.Borrow("Maya", "The Lighthouse Keeper"));
}

void Kiosk()
{
    CheckoutService checkout = new CheckoutService(new LibraryDatabase("riverside-db"), new SystemClock());
    Console.WriteLine("Kiosk: " + checkout.Borrow("Sam", "Rivers of Glass"));
}

void NightlyReminders()
{
    ReminderService reminders = new ReminderService(new LibraryDatabase("riverside-db"), new SystemClock());
    Console.WriteLine("Reminders: " + reminders.Send());
}

class LibraryDatabase { public LibraryDatabase(string address) => Console.WriteLine($"Connecting to {address}..."); }
interface IClock { DateOnly Today { get; } }
class SystemClock : IClock { public DateOnly Today => DateOnly.FromDateTime(DateTime.Today); }

class CheckoutService
{
    private readonly LibraryDatabase database;
    private readonly IClock clock;
    public CheckoutService(LibraryDatabase database, IClock clock) { this.database = database; this.clock = clock; }
    public string Borrow(string member, string title) => $"{member} borrowed {title}";
}

class ReminderService
{
    private readonly LibraryDatabase database;
    private readonly IClock clock;
    public ReminderService(LibraryDatabase database, IClock clock) { this.database = database; this.clock = clock; }
    public string Send() => "nothing due tomorrow";
}
```

```text
Connecting to riverside-db...
Website: Maya borrowed The Lighthouse Keeper
Connecting to riverside-db...
Kiosk: Sam borrowed Rivers of Glass
Connecting to riverside-db...
Reminders: nothing due tomorrow
```

```java
class LibraryDatabase { LibraryDatabase(String address) { IO.println("Connecting to " + address + "..."); } }
interface Clock { LocalDate today(); }
class SystemClock implements Clock { public LocalDate today() { return LocalDate.now(); } }

class CheckoutService {
    private final LibraryDatabase database;
    private final Clock clock;
    CheckoutService(LibraryDatabase database, Clock clock) { this.database = database; this.clock = clock; }
    String borrow(String member, String title) { return member + " borrowed " + title; }
}

class ReminderService {
    private final LibraryDatabase database;
    private final Clock clock;
    ReminderService(LibraryDatabase database, Clock clock) { this.database = database; this.clock = clock; }
    String send() { return "nothing due tomorrow"; }
}

// Each part of the app builds its own services, and everything inside them.
void website() {
    CheckoutService checkout = new CheckoutService(new LibraryDatabase("riverside-db"), new SystemClock());
    IO.println("Website: " + checkout.borrow("Maya", "The Lighthouse Keeper"));
}

void kiosk() {
    CheckoutService checkout = new CheckoutService(new LibraryDatabase("riverside-db"), new SystemClock());
    IO.println("Kiosk: " + checkout.borrow("Sam", "Rivers of Glass"));
}

void nightlyReminders() {
    ReminderService reminders = new ReminderService(new LibraryDatabase("riverside-db"), new SystemClock());
    IO.println("Reminders: " + reminders.send());
}

void main() {
    website();
    kiosk();
    nightlyReminders();
}
```

```text
Connecting to riverside-db...
Website: Maya borrowed The Lighthouse Keeper
Connecting to riverside-db...
Kiosk: Sam borrowed Rivers of Glass
Connecting to riverside-db...
Reminders: nothing due tomorrow
```

```python
from datetime import date


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


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


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

    def borrow(self, member, title):
        return f"{member} borrowed {title}"


class ReminderService:
    def __init__(self, database, clock):
        self.database = database
        self.clock = clock

    def send(self):
        return "nothing due tomorrow"


# Each part of the app builds its own services, and everything inside them.
def website():
    checkout = CheckoutService(LibraryDatabase("riverside-db"), SystemClock())
    print("Website: " + checkout.borrow("Maya", "The Lighthouse Keeper"))


def kiosk():
    checkout = CheckoutService(LibraryDatabase("riverside-db"), SystemClock())
    print("Kiosk: " + checkout.borrow("Sam", "Rivers of Glass"))


def nightly_reminders():
    reminders = ReminderService(LibraryDatabase("riverside-db"), SystemClock())
    print("Reminders: " + reminders.send())


website()
kiosk()
nightly_reminders()
```

```text
Connecting to riverside-db...
Website: Maya borrowed The Lighthouse Keeper
Connecting to riverside-db...
Kiosk: Sam borrowed Rivers of Glass
Connecting to riverside-db...
Reminders: nothing due tomorrow
```

```javascript
class LibraryDatabase { constructor(address) { console.log(`Connecting to ${address}...`); } }
class SystemClock { today() { return new Date().toISOString().slice(0, 10); } }

class CheckoutService {
  constructor(database, clock) { this.database = database; this.clock = clock; }
  borrow(member, title) { return `${member} borrowed ${title}`; }
}

class ReminderService {
  constructor(database, clock) { this.database = database; this.clock = clock; }
  send() { return "nothing due tomorrow"; }
}

// Each part of the app builds its own services, and everything inside them.
function website() {
  const checkout = new CheckoutService(new LibraryDatabase("riverside-db"), new SystemClock());
  console.log("Website: " + checkout.borrow("Maya", "The Lighthouse Keeper"));
}

function kiosk() {
  const checkout = new CheckoutService(new LibraryDatabase("riverside-db"), new SystemClock());
  console.log("Kiosk: " + checkout.borrow("Sam", "Rivers of Glass"));
}

function nightlyReminders() {
  const reminders = new ReminderService(new LibraryDatabase("riverside-db"), new SystemClock());
  console.log("Reminders: " + reminders.send());
}

website();
kiosk();
nightlyReminders();
```

```text
Connecting to riverside-db...
Website: Maya borrowed The Lighthouse Keeper
Connecting to riverside-db...
Kiosk: Sam borrowed Rivers of Glass
Connecting to riverside-db...
Reminders: nothing due tomorrow
```

```typescript
class LibraryDatabase { constructor(address: string) { console.log(`Connecting to ${address}...`); } }
interface Clock { today(): string; }
class SystemClock implements Clock { today(): string { return new Date().toISOString().slice(0, 10); } }

class CheckoutService {
  private readonly database: LibraryDatabase;
  private readonly clock: Clock;
  constructor(database: LibraryDatabase, clock: Clock) { this.database = database; this.clock = clock; }
  borrow(member: string, title: string): string { return `${member} borrowed ${title}`; }
}

class ReminderService {
  private readonly database: LibraryDatabase;
  private readonly clock: Clock;
  constructor(database: LibraryDatabase, clock: Clock) { this.database = database; this.clock = clock; }
  send(): string { return "nothing due tomorrow"; }
}

// Each part of the app builds its own services, and everything inside them.
function website(): void {
  const checkout = new CheckoutService(new LibraryDatabase("riverside-db"), new SystemClock());
  console.log("Website: " + checkout.borrow("Maya", "The Lighthouse Keeper"));
}

function kiosk(): void {
  const checkout = new CheckoutService(new LibraryDatabase("riverside-db"), new SystemClock());
  console.log("Kiosk: " + checkout.borrow("Sam", "Rivers of Glass"));
}

function nightlyReminders(): void {
  const reminders = new ReminderService(new LibraryDatabase("riverside-db"), new SystemClock());
  console.log("Reminders: " + reminders.send());
}

website();
kiosk();
nightlyReminders();
```

```text
Connecting to riverside-db...
Website: Maya borrowed The Lighthouse Keeper
Connecting to riverside-db...
Kiosk: Sam borrowed Rivers of Glass
Connecting to riverside-db...
Reminders: nothing due tomorrow
```

Three connections to one database, where one would do. A real database allows only so many connections at a time, and each one costs memory on both ends. And it gets worse with each change: when the database moves to a new address, three places need the edit; when `CheckoutService` asks for a third thing (say, an email sender), every `new CheckoutService(...)` in the app breaks.

- **The symptom:** the same `new` calls for an app's parts, copied wherever a part is needed, and the same expensive part made more than once.
- **The cause:** dependency injection moved the building out of the service, but nobody owns the building.

## What would you try?

**Make the database a Singleton, so there's only one.** That's the trap from Pass 1: the services would reach for it again, and tests would share it.

**A helper function, `makeCheckout()`, that the website and the kiosk both call.** Better: the wiring for a checkout is written once. But it still makes a new database each time it's called, unless it keeps one somewhere, and then each helper keeps its own. Follow that idea to its end and you get one place that makes *everything*, once.

## The fix: one composition root

Make every part in **one place, at the start of the app**, and hand each one to whatever needs it. That place is called the **composition root**: it's where the app is composed, or put together, from its parts. Nothing else in the app says `new` for a service.

![The composition root: at the start of the app, one place makes four parts in order, the library database (made once, shared by all), the clock, the checkout service and the reminder service, and hands each one to whatever needs it: the website, the kiosk and the nightly reminders](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/399e51dbd8f14a0a9c0efe9beea18926.webp)

```csharp
// The composition root: the one place, at the start, that makes the parts and hands them out.
LibraryDatabase database = new LibraryDatabase("riverside-db");
IClock clock = new SystemClock();
CheckoutService checkout = new CheckoutService(database, clock);
ReminderService reminders = new ReminderService(database, clock);

Website(checkout);
Kiosk(checkout);
NightlyReminders(reminders);

// The rest of the app is handed what it uses.
void Website(CheckoutService checkout) => Console.WriteLine("Website: " + checkout.Borrow("Maya", "The Lighthouse Keeper"));
void Kiosk(CheckoutService checkout) => Console.WriteLine("Kiosk: " + checkout.Borrow("Sam", "Rivers of Glass"));
void NightlyReminders(ReminderService reminders) => Console.WriteLine("Reminders: " + reminders.Send());

class LibraryDatabase { public LibraryDatabase(string address) => Console.WriteLine($"Connecting to {address}..."); }
interface IClock { DateOnly Today { get; } }
class SystemClock : IClock { public DateOnly Today => DateOnly.FromDateTime(DateTime.Today); }

class CheckoutService
{
    private readonly LibraryDatabase database;
    private readonly IClock clock;
    public CheckoutService(LibraryDatabase database, IClock clock) { this.database = database; this.clock = clock; }
    public string Borrow(string member, string title) => $"{member} borrowed {title}";
}

class ReminderService
{
    private readonly LibraryDatabase database;
    private readonly IClock clock;
    public ReminderService(LibraryDatabase database, IClock clock) { this.database = database; this.clock = clock; }
    public string Send() => "nothing due tomorrow";
}
```

```text
Connecting to riverside-db...
Website: Maya borrowed The Lighthouse Keeper
Kiosk: Sam borrowed Rivers of Glass
Reminders: nothing due tomorrow
```

```java
class LibraryDatabase { LibraryDatabase(String address) { IO.println("Connecting to " + address + "..."); } }
interface Clock { LocalDate today(); }
class SystemClock implements Clock { public LocalDate today() { return LocalDate.now(); } }

class CheckoutService {
    private final LibraryDatabase database;
    private final Clock clock;
    CheckoutService(LibraryDatabase database, Clock clock) { this.database = database; this.clock = clock; }
    String borrow(String member, String title) { return member + " borrowed " + title; }
}

class ReminderService {
    private final LibraryDatabase database;
    private final Clock clock;
    ReminderService(LibraryDatabase database, Clock clock) { this.database = database; this.clock = clock; }
    String send() { return "nothing due tomorrow"; }
}

// The rest of the app is handed what it uses.
void website(CheckoutService checkout) { IO.println("Website: " + checkout.borrow("Maya", "The Lighthouse Keeper")); }
void kiosk(CheckoutService checkout) { IO.println("Kiosk: " + checkout.borrow("Sam", "Rivers of Glass")); }
void nightlyReminders(ReminderService reminders) { IO.println("Reminders: " + reminders.send()); }

void main() {
    // The composition root: the one place, at the start, that makes the parts and hands them out.
    LibraryDatabase database = new LibraryDatabase("riverside-db");
    Clock clock = new SystemClock();
    CheckoutService checkout = new CheckoutService(database, clock);
    ReminderService reminders = new ReminderService(database, clock);

    website(checkout);
    kiosk(checkout);
    nightlyReminders(reminders);
}
```

```text
Connecting to riverside-db...
Website: Maya borrowed The Lighthouse Keeper
Kiosk: Sam borrowed Rivers of Glass
Reminders: nothing due tomorrow
```

```python
from datetime import date


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


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


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

    def borrow(self, member, title):
        return f"{member} borrowed {title}"


class ReminderService:
    def __init__(self, database, clock):
        self.database = database
        self.clock = clock

    def send(self):
        return "nothing due tomorrow"


# The rest of the app is handed what it uses.
def website(checkout):
    print("Website: " + checkout.borrow("Maya", "The Lighthouse Keeper"))


def kiosk(checkout):
    print("Kiosk: " + checkout.borrow("Sam", "Rivers of Glass"))


def nightly_reminders(reminders):
    print("Reminders: " + reminders.send())


# The composition root: the one place, at the start, that makes the parts and hands them out.
database = LibraryDatabase("riverside-db")
clock = SystemClock()
checkout = CheckoutService(database, clock)
reminders = ReminderService(database, clock)

website(checkout)
kiosk(checkout)
nightly_reminders(reminders)
```

```text
Connecting to riverside-db...
Website: Maya borrowed The Lighthouse Keeper
Kiosk: Sam borrowed Rivers of Glass
Reminders: nothing due tomorrow
```

```javascript
class LibraryDatabase { constructor(address) { console.log(`Connecting to ${address}...`); } }
class SystemClock { today() { return new Date().toISOString().slice(0, 10); } }

class CheckoutService {
  constructor(database, clock) { this.database = database; this.clock = clock; }
  borrow(member, title) { return `${member} borrowed ${title}`; }
}

class ReminderService {
  constructor(database, clock) { this.database = database; this.clock = clock; }
  send() { return "nothing due tomorrow"; }
}

// The rest of the app is handed what it uses.
const website = (checkout) => console.log("Website: " + checkout.borrow("Maya", "The Lighthouse Keeper"));
const kiosk = (checkout) => console.log("Kiosk: " + checkout.borrow("Sam", "Rivers of Glass"));
const nightlyReminders = (reminders) => console.log("Reminders: " + reminders.send());

// The composition root: the one place, at the start, that makes the parts and hands them out.
const database = new LibraryDatabase("riverside-db");
const clock = new SystemClock();
const checkout = new CheckoutService(database, clock);
const reminders = new ReminderService(database, clock);

website(checkout);
kiosk(checkout);
nightlyReminders(reminders);
```

```text
Connecting to riverside-db...
Website: Maya borrowed The Lighthouse Keeper
Kiosk: Sam borrowed Rivers of Glass
Reminders: nothing due tomorrow
```

```typescript
class LibraryDatabase { constructor(address: string) { console.log(`Connecting to ${address}...`); } }
interface Clock { today(): string; }
class SystemClock implements Clock { today(): string { return new Date().toISOString().slice(0, 10); } }

class CheckoutService {
  private readonly database: LibraryDatabase;
  private readonly clock: Clock;
  constructor(database: LibraryDatabase, clock: Clock) { this.database = database; this.clock = clock; }
  borrow(member: string, title: string): string { return `${member} borrowed ${title}`; }
}

class ReminderService {
  private readonly database: LibraryDatabase;
  private readonly clock: Clock;
  constructor(database: LibraryDatabase, clock: Clock) { this.database = database; this.clock = clock; }
  send(): string { return "nothing due tomorrow"; }
}

// The rest of the app is handed what it uses.
const website = (checkout: CheckoutService): void => console.log("Website: " + checkout.borrow("Maya", "The Lighthouse Keeper"));
const kiosk = (checkout: CheckoutService): void => console.log("Kiosk: " + checkout.borrow("Sam", "Rivers of Glass"));
const nightlyReminders = (reminders: ReminderService): void => console.log("Reminders: " + reminders.send());

// The composition root: the one place, at the start, that makes the parts and hands them out.
const database = new LibraryDatabase("riverside-db");
const clock = new SystemClock();
const checkout = new CheckoutService(database, clock);
const reminders = new ReminderService(database, clock);

website(checkout);
kiosk(checkout);
nightlyReminders(reminders);
```

```text
Connecting to riverside-db...
Website: Maya borrowed The Lighthouse Keeper
Kiosk: Sam borrowed Rivers of Glass
Reminders: nothing due tomorrow
```

One connection. When the database moves, one line changes. When `CheckoutService` asks for a third thing, one line changes. For many apps, this is all the wiring they'll ever need: a start file that makes things in order and hands them out.

## When the start file gets long: a container

A big app has hundreds of parts, not four, and some of them shouldn't live for the whole app. Each web request (one visit to `POST /loans`, say) may need its own object that holds that request's information, such as who signed in, and that object mustn't leak into the next person's request. Writing all of that by hand gets long, and the order matters: the database has to exist before the service that needs it.

A **container** is a composition root with a machine in it. You tell it, once, *how* to make each part and *how long* each part should live. Then you ask it for what you need, and it makes the parts in the right order, reusing the ones that should be shared. How long a part lives is its **lifetime**, and there are three:

| Lifetime | What it means | Good for |
|---|---|---|
| **One for the app** (often called *singleton*) | made the first time it's asked for, then shared by everyone | the database connection, the clock, settings |
| **One per request** (often called *scoped*) | made once for each web request, shared within it, thrown away after | anything that holds this request's own information, such as who signed in |
| **A new one every time** (often called *transient*) | made fresh on every ask | small parts that hold nothing between uses |

![A container's three lifetimes across two web requests: one for the app, a single database shared by both requests; one per request, a different checkout service inside each request; and a new one every time, a separate object for each ask](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/e7e33be59afb4290b5166ddd1ad8129d.webp)

Here is a whole container, small enough to read. It isn't something you'd write at work; it's here so the frameworks' containers stop being magic. It keeps a recipe for each part (its lifetime, and a function that makes it), and remembers the parts it has already made:

```csharp
Container container = new Container();
container.Register(Lifetime.OnePerApp, c => new LibraryDatabase("riverside-db"));
container.Register<IClock>(Lifetime.OnePerApp, c => new SystemClock());
container.Register(Lifetime.OnePerRequest, c => new CheckoutService(c.Get<LibraryDatabase>(), c.Get<IClock>()));

// Two web requests: each gets its own checkout service, and both share the one database.
Container request1 = container.StartRequest();
Container request2 = container.StartRequest();
CheckoutService first = request1.Get<CheckoutService>();
CheckoutService second = request2.Get<CheckoutService>();
Console.WriteLine($"Request 1: {first.Borrow("Maya", "The Lighthouse Keeper")}");
Console.WriteLine($"Request 2: {second.Borrow("Sam", "Rivers of Glass")}");
Console.WriteLine("Same checkout service all through request 1: " + (first == request1.Get<CheckoutService>() ? "yes" : "no"));
Console.WriteLine("Different checkout services for the two requests: " + (first != second ? "yes" : "no"));
Console.WriteLine("One database for both requests: " + (first.Database == second.Database ? "yes" : "no"));

enum Lifetime { OnePerApp, OnePerRequest, NewEveryTime }

// A container: a recipe for each part, and the parts it has already made.
class Container
{
    private readonly Dictionary<Type, (Lifetime Lifetime, Func<Container, object> Make)> recipes;
    private readonly Dictionary<Type, object> appParts;
    private readonly Dictionary<Type, object> requestParts = new();

    public Container() : this(new(), new()) { }

    private Container(Dictionary<Type, (Lifetime, Func<Container, object>)> recipes, Dictionary<Type, object> appParts)
    {
        this.recipes = recipes;
        this.appParts = appParts;
    }

    public void Register<T>(Lifetime lifetime, Func<Container, T> make) where T : notnull => recipes[typeof(T)] = (lifetime, c => make(c));

    // A request shares the recipes and the app's parts, and keeps its own request parts.
    public Container StartRequest() => new Container(recipes, appParts);

    public T Get<T>() where T : notnull
    {
        (Lifetime lifetime, Func<Container, object> make) = recipes[typeof(T)];
        if (lifetime == Lifetime.NewEveryTime) { return (T)make(this); }
        Dictionary<Type, object> kept = lifetime == Lifetime.OnePerApp ? appParts : requestParts;
        if (!kept.ContainsKey(typeof(T))) { kept[typeof(T)] = make(this); }
        return (T)kept[typeof(T)];
    }
}

class LibraryDatabase { public LibraryDatabase(string address) => Console.WriteLine($"Connecting to {address}..."); }
interface IClock { DateOnly Today { get; } }
class SystemClock : IClock { public DateOnly Today => DateOnly.FromDateTime(DateTime.Today); }

class CheckoutService
{
    private readonly IClock clock;
    public CheckoutService(LibraryDatabase database, IClock clock) { Database = database; this.clock = clock; }
    public LibraryDatabase Database { get; }
    public string Borrow(string member, string title) => $"{member} borrowed {title}";
}
```

```text
Connecting to riverside-db...
Request 1: Maya borrowed The Lighthouse Keeper
Request 2: Sam borrowed Rivers of Glass
Same checkout service all through request 1: yes
Different checkout services for the two requests: yes
One database for both requests: yes
```

```java
enum Lifetime { ONE_PER_APP, ONE_PER_REQUEST, NEW_EVERY_TIME }

// A container: a recipe for each part, and the parts it has already made.
class Container {
    private record Recipe(Lifetime lifetime, Function<Container, Object> make) { }

    private final Map<Class<?>, Recipe> recipes;
    private final Map<Class<?>, Object> appParts;
    private final Map<Class<?>, Object> requestParts = new HashMap<>();

    Container() { this(new HashMap<>(), new HashMap<>()); }

    private Container(Map<Class<?>, Recipe> recipes, Map<Class<?>, Object> appParts) {
        this.recipes = recipes;
        this.appParts = appParts;
    }

    <T> void register(Class<T> type, Lifetime lifetime, Function<Container, T> make) {
        recipes.put(type, new Recipe(lifetime, make::apply));
    }

    // A request shares the recipes and the app's parts, and keeps its own request parts.
    Container startRequest() { return new Container(recipes, appParts); }

    <T> T get(Class<T> type) {
        Recipe recipe = recipes.get(type);
        if (recipe.lifetime() == Lifetime.NEW_EVERY_TIME) { return type.cast(recipe.make().apply(this)); }
        Map<Class<?>, Object> kept = recipe.lifetime() == Lifetime.ONE_PER_APP ? appParts : requestParts;
        if (!kept.containsKey(type)) { kept.put(type, recipe.make().apply(this)); }
        return type.cast(kept.get(type));
    }
}

class LibraryDatabase { LibraryDatabase(String address) { IO.println("Connecting to " + address + "..."); } }
interface Clock { LocalDate today(); }
class SystemClock implements Clock { public LocalDate today() { return LocalDate.now(); } }

class CheckoutService {
    final LibraryDatabase database;
    private final Clock clock;
    CheckoutService(LibraryDatabase database, Clock clock) { this.database = database; this.clock = clock; }
    String borrow(String member, String title) { return member + " borrowed " + title; }
}

void main() {
    Container container = new Container();
    container.register(LibraryDatabase.class, Lifetime.ONE_PER_APP, c -> new LibraryDatabase("riverside-db"));
    container.register(Clock.class, Lifetime.ONE_PER_APP, c -> new SystemClock());
    container.register(CheckoutService.class, Lifetime.ONE_PER_REQUEST,
        c -> new CheckoutService(c.get(LibraryDatabase.class), c.get(Clock.class)));

    // Two web requests: each gets its own checkout service, and both share the one database.
    Container request1 = container.startRequest();
    Container request2 = container.startRequest();
    CheckoutService first = request1.get(CheckoutService.class);
    CheckoutService second = request2.get(CheckoutService.class);
    IO.println("Request 1: " + first.borrow("Maya", "The Lighthouse Keeper"));
    IO.println("Request 2: " + second.borrow("Sam", "Rivers of Glass"));
    IO.println("Same checkout service all through request 1: " + (first == request1.get(CheckoutService.class) ? "yes" : "no"));
    IO.println("Different checkout services for the two requests: " + (first != second ? "yes" : "no"));
    IO.println("One database for both requests: " + (first.database == second.database ? "yes" : "no"));
}
```

```text
Connecting to riverside-db...
Request 1: Maya borrowed The Lighthouse Keeper
Request 2: Sam borrowed Rivers of Glass
Same checkout service all through request 1: yes
Different checkout services for the two requests: yes
One database for both requests: yes
```

```python
from datetime import date


class Container:
    """A container: a recipe for each part, and the parts it has already made."""

    def __init__(self, recipes=None, app_parts=None):
        self.recipes = {} if recipes is None else recipes
        self.app_parts = {} if app_parts is None else app_parts
        self.request_parts = {}

    def register(self, kind, lifetime, make):
        self.recipes[kind] = (lifetime, make)

    def start_request(self):
        # A request shares the recipes and the app's parts, and keeps its own request parts.
        return Container(self.recipes, self.app_parts)

    def get(self, kind):
        lifetime, make = self.recipes[kind]
        if lifetime == "new every time":
            return make(self)
        kept = self.app_parts if lifetime == "one per app" else self.request_parts
        if kind not in kept:
            kept[kind] = make(self)
        return kept[kind]


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


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


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

    def borrow(self, member, title):
        return f"{member} borrowed {title}"


container = Container()
container.register(LibraryDatabase, "one per app", lambda c: LibraryDatabase("riverside-db"))
container.register(SystemClock, "one per app", lambda c: SystemClock())
container.register(CheckoutService, "one per request",
                   lambda c: CheckoutService(c.get(LibraryDatabase), c.get(SystemClock)))

# Two web requests: each gets its own checkout service, and both share the one database.
request1 = container.start_request()
request2 = container.start_request()
first = request1.get(CheckoutService)
second = request2.get(CheckoutService)
print("Request 1: " + first.borrow("Maya", "The Lighthouse Keeper"))
print("Request 2: " + second.borrow("Sam", "Rivers of Glass"))
print("Same checkout service all through request 1: " + ("yes" if first is request1.get(CheckoutService) else "no"))
print("Different checkout services for the two requests: " + ("yes" if first is not second else "no"))
print("One database for both requests: " + ("yes" if first.database is second.database else "no"))
```

```text
Connecting to riverside-db...
Request 1: Maya borrowed The Lighthouse Keeper
Request 2: Sam borrowed Rivers of Glass
Same checkout service all through request 1: yes
Different checkout services for the two requests: yes
One database for both requests: yes
```

```javascript
// A container: a recipe for each part, and the parts it has already made.
class Container {
  #recipes;
  #appParts;
  #requestParts = new Map();

  constructor(recipes = new Map(), appParts = new Map()) {
    this.#recipes = recipes;
    this.#appParts = appParts;
  }

  register(name, lifetime, make) { this.#recipes.set(name, { lifetime, make }); }

  // A request shares the recipes and the app's parts, and keeps its own request parts.
  startRequest() { return new Container(this.#recipes, this.#appParts); }

  get(name) {
    const { lifetime, make } = this.#recipes.get(name);
    if (lifetime === "new every time") { return make(this); }
    const kept = lifetime === "one per app" ? this.#appParts : this.#requestParts;
    if (!kept.has(name)) { kept.set(name, make(this)); }
    return kept.get(name);
  }
}

class LibraryDatabase { constructor(address) { console.log(`Connecting to ${address}...`); } }
class SystemClock { today() { return new Date().toISOString().slice(0, 10); } }

class CheckoutService {
  constructor(database, clock) { this.database = database; this.clock = clock; }
  borrow(member, title) { return `${member} borrowed ${title}`; }
}

const container = new Container();
container.register("database", "one per app", () => new LibraryDatabase("riverside-db"));
container.register("clock", "one per app", () => new SystemClock());
container.register("checkout", "one per request", (c) => new CheckoutService(c.get("database"), c.get("clock")));

// Two web requests: each gets its own checkout service, and both share the one database.
const request1 = container.startRequest();
const request2 = container.startRequest();
const first = request1.get("checkout");
const second = request2.get("checkout");
console.log("Request 1: " + first.borrow("Maya", "The Lighthouse Keeper"));
console.log("Request 2: " + second.borrow("Sam", "Rivers of Glass"));
console.log("Same checkout service all through request 1: " + (first === request1.get("checkout") ? "yes" : "no"));
console.log("Different checkout services for the two requests: " + (first !== second ? "yes" : "no"));
console.log("One database for both requests: " + (first.database === second.database ? "yes" : "no"));
```

```text
Connecting to riverside-db...
Request 1: Maya borrowed The Lighthouse Keeper
Request 2: Sam borrowed Rivers of Glass
Same checkout service all through request 1: yes
Different checkout services for the two requests: yes
One database for both requests: yes
```

```typescript
type Lifetime = "one per app" | "one per request" | "new every time";
type Key<T> = abstract new (...args: never[]) => T;

// A container: a recipe for each part, and the parts it has already made.
class Container {
  private readonly recipes: Map<Key<unknown>, { lifetime: Lifetime; make: (c: Container) => unknown }>;
  private readonly appParts: Map<Key<unknown>, unknown>;
  private readonly requestParts = new Map<Key<unknown>, unknown>();

  constructor(recipes = new Map(), appParts = new Map()) {
    this.recipes = recipes;
    this.appParts = appParts;
  }

  register<T>(key: Key<T>, lifetime: Lifetime, make: (c: Container) => T): void {
    this.recipes.set(key, { lifetime, make });
  }

  // A request shares the recipes and the app's parts, and keeps its own request parts.
  startRequest(): Container { return new Container(this.recipes, this.appParts); }

  get<T>(key: Key<T>): T {
    const { lifetime, make } = this.recipes.get(key)!;
    if (lifetime === "new every time") { return make(this) as T; }
    const kept = lifetime === "one per app" ? this.appParts : this.requestParts;
    if (!kept.has(key)) { kept.set(key, make(this)); }
    return kept.get(key) as T;
  }
}

class LibraryDatabase { constructor(address: string) { console.log(`Connecting to ${address}...`); } }
abstract class Clock { abstract today(): string; }
class SystemClock extends Clock { today(): string { return new Date().toISOString().slice(0, 10); } }

class CheckoutService {
  readonly database: LibraryDatabase;
  private readonly clock: Clock;
  constructor(database: LibraryDatabase, clock: Clock) { this.database = database; this.clock = clock; }
  borrow(member: string, title: string): string { return `${member} borrowed ${title}`; }
}

const container = new Container();
container.register(LibraryDatabase, "one per app", () => new LibraryDatabase("riverside-db"));
container.register(Clock, "one per app", () => new SystemClock());
container.register(CheckoutService, "one per request", (c) => new CheckoutService(c.get(LibraryDatabase), c.get(Clock)));

// Two web requests: each gets its own checkout service, and both share the one database.
const request1 = container.startRequest();
const request2 = container.startRequest();
const first = request1.get(CheckoutService);
const second = request2.get(CheckoutService);
console.log("Request 1: " + first.borrow("Maya", "The Lighthouse Keeper"));
console.log("Request 2: " + second.borrow("Sam", "Rivers of Glass"));
console.log("Same checkout service all through request 1: " + (first === request1.get(CheckoutService) ? "yes" : "no"));
console.log("Different checkout services for the two requests: " + (first !== second ? "yes" : "no"));
console.log("One database for both requests: " + (first.database === second.database ? "yes" : "no"));
```

```text
Connecting to riverside-db...
Request 1: Maya borrowed The Lighthouse Keeper
Request 2: Sam borrowed Rivers of Glass
Same checkout service all through request 1: yes
Different checkout services for the two requests: yes
One database for both requests: yes
```

"Connecting" prints once: the database is one for the app, made the first time the first request asked for a checkout service. Each request got its own checkout service, and kept it for the whole request.

**Where the languages differ.** C#, Java and TypeScript look parts up by their type (`Get<CheckoutService>()`, `CheckoutService.class`, the class itself), as the real containers do; TypeScript makes `Clock` an abstract class instead of an interface, because an interface disappears when the program runs and can't be looked up. Python looks parts up by class too. JavaScript has no types to look up by, so its container names each part with a word.

Real containers do one more thing ours doesn't: they read a class's constructor and work out what to hand in by themselves, so `AddScoped<CheckoutService>()` is all you write. That's why it feels like magic. Underneath, it's this.

## What this looks like in a framework

These aren't run here: each needs its framework's project around it. Each tab is that language's composition root, registering the same three parts. Versions checked on 2026-11-01.

```csharp
// ASP.NET Core 10, Program.cs: the composition root. The container reads each class's
// constructor and hands in what it asks for.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(new LibraryDatabase("riverside-db")); // one for the app
builder.Services.AddSingleton(TimeProvider.System);                 // one for the app
builder.Services.AddScoped<CheckoutService>();                      // one per request
builder.Services.AddTransient<ReminderService>();                   // a new one every time

var app = builder.Build();
app.MapPost("/loans", (LoanRequest body, CheckoutService checkout) => checkout.Borrow(body.Member, body.Title));
app.Run();
```

```java
// Spring Boot 4.1: a @Configuration class is part of the composition root. Spring makes one
// of each @Bean for the whole app unless told otherwise; @RequestScope makes one per request,
// and @Scope("prototype") a new one every time.
import java.time.Clock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.annotation.RequestScope;

@Configuration
public class LibraryWiring {
    @Bean
    LibraryDatabase libraryDatabase() { return new LibraryDatabase("riverside-db"); }

    @Bean
    Clock clock() { return Clock.systemDefaultZone(); }

    @Bean
    @RequestScope
    CheckoutService checkoutService(LibraryDatabase database, Clock clock) {
        return new CheckoutService(database, clock);
    }
}
```

```python
# FastAPI 0.162: no container. A dependency function runs once per request (FastAPI reuses
# its answer within that request), and @lru_cache makes its answer one for the whole app.
from datetime import date
from functools import lru_cache
from typing import Annotated

from fastapi import Depends, FastAPI

from library import CheckoutService, LibraryDatabase

app = FastAPI()


@lru_cache
def get_database() -> LibraryDatabase:
    return LibraryDatabase("riverside-db")


def get_checkout(database: Annotated[LibraryDatabase, Depends(get_database)]) -> CheckoutService:
    return CheckoutService(database, date.today)


@app.post("/loans")
def borrow(member: str, title: str, checkout: Annotated[CheckoutService, Depends(get_checkout)]):
    return checkout.borrow(member, title)
```

```javascript
// Express 5.3: no container. The start file is the composition root, written by hand,
// and a small step at the front of each request makes that request's own parts.
import express from "express";
import { CheckoutService, LibraryDatabase } from "./library.js";

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

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

```typescript
// NestJS 12.3: a module lists its providers, and Nest's container makes them. One for the
// app is the default; Scope.REQUEST makes one per request, Scope.TRANSIENT a new one every time.
import { Module, Scope } from "@nestjs/common";
import { CheckoutService, Clock, LibraryDatabase, SystemClock } from "./library";
import { LoansController } from "./loans.controller";

@Module({
  controllers: [LoansController],
  providers: [
    { provide: LibraryDatabase, useValue: new LibraryDatabase("riverside-db") },
    { provide: Clock, useClass: SystemClock },
    { provide: CheckoutService, useClass: CheckoutService, scope: Scope.REQUEST },
  ],
})
export class LibraryModule {}
```

In Angular, `@Injectable({ providedIn: "root" })` on a class makes it one for the whole app, and a component's own `providers` list gives that component its own.

## Why Python and JavaScript apps often skip the container

FastAPI and Express have no container, and many Python and JavaScript teams never miss one. Their apps tend to be smaller, both languages let any function be handed in without an interface, and a module (a file) is already one shared object, made once. So they write the composition root by hand, in the start file, as this lesson's second program did. It's the same pattern: one place makes the parts and hands them out. The container is a convenience for big apps, not the idea itself.

## When not to use a container

- **When the start file is short.** Ten lines of `new`, in order, are easier to read than a container's registrations, and a mistake shows up when the program starts.
- **When it turns into a place to look things up from.** Asking the container for a part from deep inside a class (`container.Get<Clock>()`) hides what the class needs again: that's the look-up place from the last lesson. Ask for parts in constructors, and let only the composition root talk to the container.
- **When a lifetime is picked without thinking.** Something "one per request" handed to something "one for the app" lives for the whole app by accident, and one person's request data can leak into the next. Give a part the shortest lifetime it can have.

**How often you'll meet it:** every day in ASP.NET Core, Spring and Angular; now and then in Python and JavaScript (our estimate).

## Check yourself

2 questions to try on the lesson page.

## So what

Dependency injection asks "who makes the parts?", and the answer is "one place, at the start". In a small app that place is a few lines you write by hand. In a big one it's a container, and now you know what it's doing: following your recipes, in the right order, and remembering what it has already made.

## Key terms

- [Inversion of Control Container](https://www.ask-codey.com/glossary/inversion-of-control-container)
- [Composition Root](https://www.ask-codey.com/glossary/composition-root)
- [Service Lifetime](https://www.ask-codey.com/glossary/service-lifetime-oop)
- [Dependency Injection](https://www.ask-codey.com/glossary/dependency-injection)

## Cheat sheets

- [Containers: Who Does the Handing Out](https://www.ask-codey.com/cheat-sheets/dp-di-containers-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-di-containers
