Skip to content

Lesson 5 of 9 · 22m

Dependency Injection Without Framework Magic

Constructor injection, composition roots, and lifetimes — how to get testability and explicit dependencies without turning configuration into a second programming language.

Dependency injection is not a framework. It is a discipline: objects receive what they need instead of constructing or discovering it themselves. Frameworks can automate the wiring, but the important part is the dependency graph you choose.

The core move

class InvoiceMailer:
    def __init__(self, smtp: SmtpClient, templates: TemplateRenderer, clock: Clock):
        self.smtp = smtp
        self.templates = templates
        self.clock = clock

    def send_overdue_notice(self, invoice: Invoice) -> None:
        body = self.templates.render("overdue", invoice=invoice, today=self.clock.today())
        self.smtp.send(invoice.customer.email, "Invoice overdue", body)

This class does not know how SMTP is configured, where templates live, or whether time is real. Tests can pass fakes; production can pass real adapters. No container is required.

Compose at the root

Construct shared infrastructure once, near application startup, then wire the graph explicitly.

def create_app(settings: Settings) -> App:
    clock = SystemClock()
    smtp = SmtpClient(settings.smtp_host, settings.smtp_port, timeout=5)
    renderer = TemplateRenderer(settings.template_dir)
    invoice_mailer = InvoiceMailer(smtp, renderer, clock)
    return App(invoice_mailer=invoice_mailer)

This composition root is the architectural map. When a dependency graph is explicit, a new hire can inspect startup and understand what exists.

Lifetime mistakes cause production incidents

The classic DI failure is capturing a short-lived dependency inside a long-lived object. A singleton holding a request-scoped database session corrupts data or leaks state between users. Learn three lifetimes:

  • singleton: one instance for process lifetime; good for stateless clients and pools
  • scoped: one per request/job; good for transactions and unit-of-work state
  • transient: new each use; good for stateful objects with independent mutable state

Frameworks make lifetime easy to declare and easy to get wrong. Explicit construction forces you to look at it.

Inject behavior, not configuration soup

Passing a primitive value is fine when it is truly input. Passing thirty raw configuration keys means the object does not know what it is. Prefer cohesive configuration objects or behavior interfaces.

// weaker
constructor(host: string, port: number, timeout: number, retries: number, username: string) {}

// stronger
constructor(private smtp: SmtpClient) {}

When containers help

Containers earn their keep in large graphs with decorators, scoped lifetimes, and many consumers. They hurt when registration indirection becomes more complicated than the construction it replaced. If resolving a dependency requires scanning XML, attributes, module scanning, and conditional registrations, the framework is now part of the problem.

Field notes

  • Constructor injection exposes dependency bloat; if a constructor hurts to read, the object may have too many responsibilities.
  • Never inject a service locator into everything — that recreates global lookup with extra steps.
  • Clocks, randomness, network, filesystem, and persistence are the first dependencies to make explicit because tests need control over them.

Was this lesson helpful?

Sign in to rate