Skip to content

Lesson 2 of 9 · 24m

Dependency Injection: Lifetimes, Not Magic

What FastAPI dependencies really are, how request-scoped resources should behave, and how to use DI for testability without building a framework inside the framework.

Dependency injection in FastAPI looks elegant in examples and mysterious in incidents. The mental model is simple: Depends means 'call this function first and pass its return value.' If it yields, the code after yield is cleanup. Everything else — caching, overrides, nested dependencies — follows from that.

Dependencies are construction, not business logic

from collections.abc import Iterator
from fastapi import Depends
from sqlalchemy.orm import Session

def get_db() -> Iterator[Session]:
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/accounts/{account_id}")
def read_account(account_id: int, db: Session = Depends(get_db)):
    return db.get(Account, account_id)

The dependency's job is to produce a correctly scoped resource. Queries, validation of domain rules, and orchestration belong in the endpoint or service layer. Once a dependency starts making authorization decisions plus opening connections plus formatting responses, nobody can test it in isolation.

Request scope is the default mental model

FastAPI caches a dependency result within one request when the same dependency is requested multiple times. That is good: two collaborators share the same database session. But do not mistake that for global reuse. A dependency that creates a connection must close it after the response finishes.

The production failure mode is a generator dependency with no cleanup or cleanup that swallows exceptions. Put cleanup in finally, and let rollback/commit semantics be explicit:

def get_db() -> Iterator[Session]:
    db = SessionLocal()
    try:
        yield db
    except Exception:
        db.rollback()
        raise
    finally:
        db.close()

Override at boundaries in tests

FastAPI's dependency_overrides is powerful because it lets tests replace infrastructure, not because it lets you skip design:

app.dependency_overrides[get_db] = lambda: test_db_session

Use it for databases, clock providers, message buses, and external clients. Do not override half the application to make a test pass; that means the endpoint is doing too much.

Singletons are configuration, not hidden state

A database engine or HTTP client pool can be module-level because it is designed for reuse. Request state cannot. Mutable globals passed through dependencies create the classic bug where one user's tenant, feature flag, or transaction leaks into another request.

Field notes

  • Depends runs per request; do not put expensive service discovery in it unless it is cached deliberately.
  • A dependency should either be infrastructure or a narrow policy object. Mixed responsibilities become untestable.
  • Async dependencies are worth it only when they actually await I/O; async wrappers around blocking calls still block the worker.
  • Use dependency overrides sparingly and reset them after tests with app.dependency_overrides.clear().

Was this lesson helpful?

Sign in to rate