Constructor Injection is a Dependency Injection technique where dependencies are provided through a class constructor. This is the most common and recommended form of DI.
How It Works
Instead of creating dependencies internally, a class declares them as constructor parameters:
class UserService:
def __init__(self, database_service: DatabaseService):
self.database_service = database_service
def get_user(self, user_id):
return self.database_service.fetch_user(user_id)The caller is responsible for providing the dependency:
db = DatabaseService()
user_service = UserService(db)Why It’s Preferred
- Explicit — Dependencies are visible in the signature
- Valid state — Object is fully initialized after construction
- Immutable — Dependencies can be set once and not changed
Other Injection Techniques
- Setter Injection — Dependencies provided through setter methods after construction. Useful when dependencies are optional.
- Interface Injection — The class implements an interface that defines an injection method (e.g.,
set_dependency(dep)). The injector calls this method to provide the dependency. Less common in practice.
TIP
Prefer constructor injection. Use setter injection only for optional dependencies.