32. Dependency Injection

Here are 10 Python code snippets demonstrating dependency injection techniques that help with managing dependencies in Python applications to improve flexibility and testability:


1. Basic Constructor Injection

class Database:
    def connect(self):
        return "Connected to the database."

class Service:
    def __init__(self, db: Database):
        self.db = db

    def get_data(self):
        return self.db.connect()

# Creating instances
db = Database()
service = Service(db)
print(service.get_data())

2. Dependency Injection via Setter Method


3. Dependency Injection with Function Injection


4. Using Dependency Injection with a Context Manager


5. Dependency Injection via a Factory Function


6. Using Dependency Injection with a Simple DI Container


7. Using Dependency Injection with Class Inheritance


8. Using Dependency Injection with Abstract Base Classes


9. Dependency Injection for Unit Testing


10. Using Dependency Injection with injector Library

Install injector with pip install injector.


These examples show various ways to implement dependency injection in Python, including constructor injection, setter injection, factory methods, DI containers, and using popular libraries like injector. Dependency injection helps to decouple components and makes code more testable and flexible.

Last updated