惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
T
The Blog of Author Tim Ferriss
F
Fortinet All Blogs
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
阮一峰的网络日志
阮一峰的网络日志
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
MyScale Blog
MyScale Blog
雷峰网
雷峰网
博客园 - 叶小钗
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
GbyAI
GbyAI
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 三生石上(FineUI控件)
云风的 BLOG
云风的 BLOG
V
V2EX
宝玉的分享
宝玉的分享
酷 壳 – CoolShell
酷 壳 – CoolShell
N
Netflix TechBlog - Medium
Vercel News
Vercel News
美团技术团队
人人都是产品经理
人人都是产品经理
The Cloudflare Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
When Python Manual Wiring Turns Into Copy-Paste Architecture
Vlad Shulcz · 2026-05-26 · via DEV Community

Vlad Shulcz

I usually avoid dependency injection containers in Python.

Not because dependency injection is bad. Most of us already do it when we pass objects into constructors. I avoid containers because small Python apps usually do not need one.

Manual wiring is often the right starting point:

repo = UserRepository()
email_sender = EmailSender()
register_user = RegisterUser(repo, email_sender)

That is explicit, easy to debug, and boring in a good way.

The problem starts when this code stops living in one place.

The Code Drifts

The same services need to be created across completely different entrypoints.

In api/routes.py:

register_user = RegisterUser(UserRepository(), EmailSender())

In cli/commands.py:

# Oops, forgot to update this one when dependencies changed?
register_user = RegisterUser(UserRepository(), MockEmailSender())

The code does not fail all at once. It drifts.

One entrypoint gets a new dependency:

register_user = RegisterUser(repo, email_sender, audit_log)

Another still creates the old version. A test uses a fake for one service but accidentally keeps a real client for another. A worker starts fine, then fails only when the first real job touches the missing path.

That is the kind of boring failure I wanted to avoid. It was not a big architecture disaster. It was worse in a boring way: tiny setup details repeated in enough places that forgetting one became easy.

The problem is not dependency injection

Most Python code already uses dependency injection in the boring sense:

class RegisterUser:
    def __init__(self, repo: UserRepository, email_sender: EmailSender):
        self.repo = repo
        self.email_sender = email_sender

The class is fine. It receives dependencies instead of creating them.

The mess appears around the class, when every entrypoint has to remember how to build the same graph.

Framework DI stops at the framework boundary

FastAPI Depends is useful. Framework dependency systems are good when the framework owns the entrypoint.

But application services often need to run elsewhere:

  • maintenance commands;
  • scheduled jobs;
  • message consumers;
  • tests;
  • local scripts.

I do not want my service layer to care whether it is being called from an API route, a CLI command, or a worker. Construction can stay at the edge. The service layer can stay plain.

I wanted something smaller than a full DI container

Python already has mature DI libraries. Some of them support provider objects, configuration systems, framework integrations, and dozens of advanced features.

That is useful if you need it. I wanted a smaller tool for the middle ground:

  • Normal constructor injection (no magic syntax).
  • Type hints as the wiring contract.
  • Singleton, transient, and scoped lifetimes.
  • Temporary overrides in tests.
  • Validation before startup.
  • Zero runtime dependencies & no decorators required on your services.

I built injex as one attempt at that middle ground.

Here is how the wiring can live in one place.

In a real app, these classes would live in separate modules. They are inline here to keep the example short:

# app/ioc.py
from abc import ABC, abstractmethod
from injex import Container

class UserRepository(ABC):
    @abstractmethod
    def save(self, email: str) -> int: ...

class SqlUserRepository(UserRepository):
    def save(self, email: str) -> int:
        return 42

class EmailSender:
    def send_welcome(self, email: str) -> None:
        print(f"Welcome, {email}")

class RegisterUser:
    def __init__(self, repo: UserRepository, email_sender: EmailSender):
        self.repo = repo
        self.email_sender = email_sender

    def execute(self, email: str) -> int:
        return self.repo.save(email)

# Centralized configuration
container = Container()

# Bind abstract interfaces to concrete implementations
container.add_singleton(UserRepository, SqlUserRepository)
container.add_singleton(EmailSender)
container.add_transient(RegisterUser)

container.assert_valid()

Now each entrypoint uses the same graph.

In your api/routes.py or cli/commands.py, you just resolve what you need:

from app.ioc import container, RegisterUser

use_case = container.resolve(RegisterUser)
use_case.execute("ada@example.com")

The service class stays plain Python. No decorators, no base class, no framework imports. The container only owns construction.

The part I care about most: validation

The most useful feature for me is not resolving objects. It is finding broken wiring before anything important runs.

If a dependency is missing, or a constructor annotation is wrong, I want to know at startup. Not after the first HTTP request. Not after the first worker job. Not in a rarely used CLI path at 3 AM.

container.assert_valid()

If you forgot to register AuditLog, startup fails immediately with a clear error:

Container validation failed with 1 error(s):
- RegisterUser: Dependency 'audit_log' is not registered: AuditLog.

Or you can collect errors explicitly in your CI/CD sanity-check script:

errors = container.validate()

if errors:
    for error in errors:
        print(error)
    raise SystemExit(1)

The crucial detail is that validation checks the dependency graph without constructing service instances. That matters when constructors open files, spin up thread pools, or establish heavy database connections.

Test overrides

Tests are where copy-pasted wiring becomes especially annoying.

You either rebuild the whole graph for each test, or you mutate shared setup and hope it gets restored correctly. I wanted replacement to be explicit and temporary:

class FakeEmailSender:
    def __init__(self):
        self.sent_to = []

    def send_welcome(self, email: str) -> None:
        self.sent_to.append(email)

fake_sender = FakeEmailSender()

# Explicit context manager for tests
with container.override(EmailSender, instance=fake_sender):
    use_case = container.resolve(RegisterUser)
    use_case.execute("test@example.com")

assert fake_sender.sent_to == ["test@example.com"]
# Outside the block, the original configuration is restored.

That keeps tests explicit without permanently mutating the production container or introducing side effects.

Scoped lifetimes

Some objects should live for one request, one job, or one message, but not for the whole lifecycle of the process.

class RequestContext:
    pass

container.add_scoped(RequestContext)

scope_a = container.create_scope()
scope_b = container.create_scope()

assert scope_a.resolve(RequestContext) is scope_a.resolve(RequestContext)
assert scope_a.resolve(RequestContext) is not scope_b.resolve(RequestContext)

This is ideal for message consumers (like Celery or RabbitMQ workers) that reuse long-lived clients but still need isolated per-job state.

Multiple implementations

Sometimes resolving one implementation is wrong. You want every handler, plugin, or pipeline step registered for the same interface.

container.add_singleton(Notifier, EmailNotifier)
container.add_singleton(Notifier, SlackNotifier)

# Resolve all registered implementations at once
for notifier in container.resolve_all(Notifier):
    notifier.notify("Deployment complete")

That is enough for simple fan-out notifications, plugin architectures, and processing pipelines.

When I would not use it

A container should pay rent. I would still skip one if:

  • the wiring fits in one file;
  • there is only one entrypoint;
  • tests can easily pass fakes directly via standard constructors;
  • the framework dependency system (like FastAPI) already covers 100% of your operational surface;
  • the project needs a massive provider/configuration ecosystem.

Manual wiring is still the baseline. A container should only appear when it removes repeated construction code instead of adding ceremony.

Closing

I am not trying to make Python look like Java. I still prefer manual wiring when an application is small enough.

I built injex for the awkward middle: the graph is repeated enough to hurt, but not complex enough to justify a large provider framework. It is small, type-hint driven, zero-dependency, and focused entirely on explicit app wiring.

If you have run into this problem in Python services, CLIs, workers, or tests, I would appreciate your feedback on the API and examples!

Links: