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

推荐订阅源

Security Archives - TechRepublic
Security Archives - TechRepublic
D
Docker
D
DataBreaches.Net
V
Vulnerabilities – Threatpost
P
Palo Alto Networks Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
IT之家
IT之家
L
LINUX DO - 热门话题
T
The Blog of Author Tim Ferriss
雷峰网
雷峰网
Project Zero
Project Zero
T
Threatpost
D
Darknet – Hacking Tools, Hacker News & Cyber Security
宝玉的分享
宝玉的分享
Stack Overflow Blog
Stack Overflow Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Securelist
Cisco Talos Blog
Cisco Talos Blog
Google DeepMind News
Google DeepMind News
Scott Helme
Scott Helme
The Cloudflare Blog
Know Your Adversary
Know Your Adversary
T
Tor Project blog
博客园_首页
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
Security Latest
Security Latest
Cyberwarzone
Cyberwarzone
S
Schneier on Security
T
The Exploit Database - CXSecurity.com
H
Help Net Security
Simon Willison's Weblog
Simon Willison's Weblog
阮一峰的网络日志
阮一峰的网络日志
C
Cyber Attacks, Cyber Crime and Cyber Security
P
Proofpoint News Feed
AWS News Blog
AWS News Blog
The GitHub Blog
The GitHub Blog
P
Proofpoint News Feed
T
Troy Hunt's Blog
量子位
G
GRAHAM CLULEY
O
OpenAI News
Engineering at Meta
Engineering at Meta
博客园 - Franky
SecWiki News
SecWiki News
F
Fortinet All Blogs
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
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: