Skip to content

017. Dependency injection framework: dependency-injector

  • Date: 2026-06-15
  • Status: Accepted
  • In the context of a growing FastAPI + Lambda ingestion app where infrastructure objects (BedrockEmbedder, BedrockLLM, DB connection factory) are constructed at call sites in pipeline.py and app.py,
  • facing fragile test setup (module-level unittest.mock.patch intercepts that break on refactor) and compounding wiring complexity as routes and Lambda handlers multiply,
  • we decided for dependency-injector with a DeclarativeContainer in rag_sample/container.py — each infrastructure object declared as a providers.Singleton or providers.Factory; FastAPI routes and ingestion functions receive dependencies from the container rather than constructing them directly; tests use container.override() to inject stubs with no patch needed,
  • and neglected
    • Manual kwarg defaults (def embed(embedder=None): if embedder is None: embedder = BedrockEmbedder()) — zero new dependencies, but per-function optional-parameter wiring scales poorly and test setup stays verbose
    • lagom — auto-wires by type annotation with less boilerplate; rejected for low adoption (289K vs 5.25M monthly downloads as of 2026-06-15) and fewer production references
    • FastAPI Depends() — fits per-request HTTP dependencies but does not address ingestion pipeline wiring or Lambda handler setup outside the request lifecycle
  • to achieve explicit, auditable wiring declared once in the container, with zero patch calls in tests and a single-point swap for provider substitution (e.g. local embedder for dev),
  • accepting a new framework dependency that is Python-only and carries no AWS or FastAPI opinions.
  • rag_sample/container.py owns all infrastructure wiring; consumers import the container, not concrete classes directly.
  • Adding a new provider (e.g. OpenAI embedder for dev) requires one new provider declaration in the container and a config toggle — no changes to call sites.
  • The framework is Python-only and has no AWS or FastAPI opinions, so it does not constrain future infrastructure choices.