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

Copy

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

Copy


3. Dependency Injection with Function Injection

Copy


4. Using Dependency Injection with a Context Manager

Copy


5. Dependency Injection via a Factory Function

Copy


6. Using Dependency Injection with a Simple DI Container

Copy


7. Using Dependency Injection with Class Inheritance

Copy


8. Using Dependency Injection with Abstract Base Classes

Copy


9. Dependency Injection for Unit Testing

Copy


10. Using Dependency Injection with injector Library

Copy

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