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

推荐订阅源

博客园 - Franky
D
Docker
Jina AI
Jina AI
The GitHub Blog
The GitHub Blog
博客园 - 聂微东
B
Blog RSS Feed
大猫的无限游戏
大猫的无限游戏
M
MIT News - Artificial intelligence
Vercel News
Vercel News
Microsoft Security Blog
Microsoft Security Blog
博客园 - 叶小钗
爱范儿
爱范儿
D
DataBreaches.Net
Hugging Face - Blog
Hugging Face - Blog
IT之家
IT之家
Recent Announcements
Recent Announcements
U
Unit 42
腾讯CDC
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
宝玉的分享
宝玉的分享
量子位
Stack Overflow Blog
Stack Overflow Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Azure Blog
Microsoft Azure 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
InjectQ: The Modern Python Dependency Injection Library
Shudipto Tra · 2026-05-18 · via DEV Community

Shudipto Trafder

The Pain of Python Apps (And How InjectQ Fixes It)

Ever built a Python app that started simple but slowly turned into a tangled web of dependencies?
Where changing one component breaks another?
Where testing becomes painful and dependency management spirals out of control?

You’re not alone.

Most Python developers eventually hit the same problems:

  • Tight coupling between components
  • Difficult-to-test business logic
  • Manual dependency wiring everywhere
  • Async code that becomes messy over time

Traditional dependency injection frameworks often make things worse:

  • Verbose configuration
  • Complex setup
  • Poor async support
  • Too much boilerplate

That’s where InjectQ comes in.

InjectQ is a lightweight, modern dependency injection library for Python that feels intuitive from day one.
It’s as simple as using a dictionary, yet powerful enough for enterprise-grade applications.

Built for modern Python:

  • Async-first
  • Type-safe
  • Thread-safe
  • FastAPI-ready
  • FastMCP-ready
  • Taskiq-ready

5-Minute Setup

Install InjectQ:

pip install injectq

Enter fullscreen mode Exit fullscreen mode

Your First InjectQ App

from injectq import InjectQ, inject, singleton

container = InjectQ.get_instance()


@singleton
class Database:
    def __init__(self):
        print("DB connected!")


@singleton
class UserService:
    def __init__(self, db: Database):
        self.db = db

    def get_user(self, user_id: int):
        return {
            "id": user_id,
            "name": "Alice",
        }


@inject
def main(service: UserService):
    user = service.get_user(1)
    print(user)


if __name__ == "__main__":
    main()

Enter fullscreen mode Exit fullscreen mode

Output

DB connected!
{'id': 1, 'name': 'Alice'}

Enter fullscreen mode Exit fullscreen mode

No manual wiring.
No container plumbing.
Just clean, testable Python code.


Why InjectQ?

1. Dictionary-Simple API

InjectQ keeps dependency management intuitive.

Register values, classes, or instances using familiar dictionary syntax:

from injectq import InjectQ

container = InjectQ.get_instance()

container[str] = "Hello World"
container[Database] = Database

message = container[str]
db = container[Database]

Enter fullscreen mode Exit fullscreen mode

Perfect for:

  • Rapid prototyping
  • Config management
  • Lightweight applications
  • Enterprise services

2. Automatic Injection with @inject

The @inject decorator resolves dependencies automatically using type hints.

Works with:

  • Functions
  • Class methods
  • Static methods
  • Async functions
from injectq import inject


@inject
def process_user(user_id: int, service: UserService):
    return service.get_user(user_id)


result = process_user(123)

Enter fullscreen mode Exit fullscreen mode

No need to pass service manually.


3. Lazy Injection with Inject[T]

Need optional or deferred dependencies?

Use Inject[T] for lazy resolution.

from injectq import Inject


def handle_request(
    data: dict,
    service: UserService = Inject[UserService],
):
    return service.get_user(data["id"])

Enter fullscreen mode Exit fullscreen mode

Dependencies resolve only when accessed.

Benefits:

  • Faster startup time
  • Lower memory usage
  • Cleaner optional dependency handling

4. Powerful Factory Support

InjectQ supports runtime-aware factories with mixed injected and manual parameters.

from injectq import InjectQ

container = InjectQ.get_instance()


class UserHandler:
    def __init__(self, db: Database, user_id: str):
        self.db = db
        self.user_id = user_id


def create_handler(db: Database, user_id: str):
    return UserHandler(db, user_id)


container.bind_factory("handler", create_handler)

handler = container.invoke("handler", user_id="alice")

Enter fullscreen mode Exit fullscreen mode

Ideal for:

  • Request-specific objects
  • Multi-tenant systems
  • Background jobs
  • Dynamic runtime construction

5. Lifecycle & Scope Control

Control object lifecycles precisely.

from injectq import singleton, scoped, transient


@singleton
class DatabasePool:
    pass


@scoped("request")
class RequestContext:
    pass


@transient
class Validator:
    pass

Enter fullscreen mode Exit fullscreen mode

Available Scopes

Scope Behavior
@singleton One instance for the entire application
@scoped() One instance per scope/context
@transient New instance every resolution

Perfect for:

  • Database pools
  • Request contexts
  • Per-task resources
  • Stateless utilities

6. Async-First by Design

InjectQ was built for modern async Python.

from injectq import inject


@inject
async def async_task(service: AsyncService):
    return await service.process()


result = await async_task()

Enter fullscreen mode Exit fullscreen mode

Supports:

  • Async dependency resolution
  • Async factories
  • Async scopes
  • Async frameworks

No hacks. No wrappers. Native async support.


Framework Integrations

InjectQ integrates seamlessly with modern Python frameworks.


FastAPI Integration

from typing import Annotated

from fastapi import FastAPI
from injectq import InjectQ
from injectq.integrations.fastapi import (
    InjectFastAPI,
    setup_fastapi,
)

app = FastAPI()

container = InjectQ.get_instance()

setup_fastapi(container, app)


@app.get("/users/{user_id}")
async def get_user(
    user_id: int,
    service: Annotated[
        UserService,
        InjectFastAPI(UserService),
    ],
):
    return service.get_user(user_id)

Enter fullscreen mode Exit fullscreen mode

Features:

  • Request-scoped dependencies
  • Type-safe injection
  • Async-native support
  • Clean route handlers

Taskiq Integration

Background job processing becomes clean and maintainable.

from typing import Annotated

from taskiq import InMemoryBroker
from injectq.integrations.taskiq import (
    InjectTaskiq,
    setup_taskiq,
)

broker = InMemoryBroker()

setup_taskiq(container, broker)


@broker.task
async def process_order(
    order_id: int,
    service: Annotated[
        OrderService,
        InjectTaskiq(OrderService),
    ],
):
    return await service.process(order_id)

Enter fullscreen mode Exit fullscreen mode

Perfect for:

  • Async workers
  • Distributed tasks
  • Queue processing
  • Event-driven systems

FastMCP Integration

Build clean, dependency-injected MCP servers effortlessly.

from typing import Annotated

from fastmcp import FastMCP
from injectq import InjectQ
from injectq.integrations.fastmcp import (
    InjectFastMCP,
    setup_fastmcp,
)

mcp = FastMCP("example-server")

container = InjectQ.get_instance()

setup_fastmcp(container, mcp)


@mcp.tool()
async def get_user(
    user_id: int,
    service: Annotated[
        UserService,
        InjectFastMCP(UserService),
    ],
):
    return service.get_user(user_id)

Enter fullscreen mode Exit fullscreen mode

Ideal for:

  • AI tools
  • MCP servers
  • Agent platforms
  • LLM applications

Performance That Impresses

InjectQ is designed for speed.

Benchmarks

Metric Performance
Dependency Resolution ~1µs
10-Service Web Request ~142µs
DI Throughput 7,000+ req/sec

Even deep dependency trees resolve extremely fast.

Built with:

  • Thread safety
  • Zero unnecessary locks
  • Optimized async execution
  • Minimal overhead

Why Developers Choose InjectQ

  • Simple and intuitive API
  • Async-first architecture
  • Excellent performance
  • Type-safe dependency injection
  • Lightweight and minimal
  • Production-ready scopes
  • FastAPI integration
  • Taskiq integration
  • FastMCP integration
  • Enterprise-friendly design

Whether you're building:

  • Scripts
  • APIs
  • Background workers
  • MCP servers
  • Enterprise systems

InjectQ scales with your application.


Get Started

Install:

pip install injectq

Enter fullscreen mode Exit fullscreen mode

Documentation:

InjectQ Docs

GitHub Repository:

InjectQ GitHub

Start building cleaner, faster, and more maintainable Python applications with InjectQ.