Junior — Middle
What methods can be used to implement dependency injection between classes in software?
sobes.tech AI
Answer from AI
Dependency Injection (DI) is a pattern that allows passing dependencies (objects, services) into a class from outside rather than creating them inside the class. In Python, this can be implemented in several ways:
- Constructor Injection Dependencies are passed through the class constructor:
class Service:
pass
class Client:
def __init__(self, service: Service):
self.service = service
service = Service()
client = Client(service)
- Setter Injection Dependencies are set through methods:
class Client:
def set_service(self, service: Service):
self.service = service
client = Client()
client.set_service(service)
- Property Injection Dependencies are assigned directly to attributes:
client = Client()
client.service = service
- Using DI frameworks
For example,
dependency_injector— a library for managing dependencies.
The main idea is to separate the creation of dependencies from their use, which facilitates testing and maintenance of the code.