Skip to content
Dependency Injection — Explained with Examples

Dependency Injection — Explained with Examples

DodaTech Updated Jun 15, 2026 2 min read

Dependency Injection is a technique where objects receive their dependencies from an external source rather than creating them internally.

Dependency Injection (DI) is a design pattern that implements the Dependency Inversion Principle. Instead of a class instantiating its own dependencies, they are “injected” through the constructor, setter methods, or an interface. A DI container often manages the wiring automatically.

Why DI Matters

Hard-coded dependencies make classes rigid, hard to test, and impossible to reuse in different contexts. DI decouples the creation of dependencies from their consumption. You can swap implementations, provide mocks in tests, and change behavior without modifying the dependent class.

Real-World Analogy

A chef doesn’t grow their own vegetables or raise their own chickens. Ingredients (dependencies) are delivered by suppliers. The chef focuses on cooking. If the chef wants organic tomatoes, a new supplier delivers them — the chef doesn’t change their cooking technique. DI is the supplier delivering what the class needs.

Example: Constructor Injection

from abc import ABC, abstractmethod

class Logger(ABC):
    @abstractmethod
    def log(self, message: str): pass

class ConsoleLogger(Logger):
    def log(self, message: str):
        print(f"[Console] {message}")

class FileLogger(Logger):
    def log(self, message: str):
        with open("app.log", "a") as f:
            f.write(f"{message}\n")

class UserService:
    # Dependency injected via constructor
    def __init__(self, logger: Logger):
        self.logger = logger

    def create_user(self, name: str):
        # business logic...
        self.logger.log(f"User created: {name}")

# Inject ConsoleLogger
service = UserService(ConsoleLogger())
service.create_user("Alice")
# Output: [Console] User created: Alice

# Inject FileLogger — same class, different behavior
service2 = UserService(FileLogger())
service2.create_user("Bob")
# Output: (writes to app.log)

Related Terms

Dependency Inversion Principle, Factory Pattern, Singleton Pattern, Repository Pattern

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro