Service Locator Сервис локатор - что это такое, альтернатива инъекции зависимости DI
What is Dependency Injection and Service Locator?
Introduction to Dependencies
- The discussion begins with a question about the nature of dependencies, specifically whether they are an infection or an implementation.
- It is noted that a dependency can be simply a call to another method, but this definition may not encompass all scenarios.
Understanding Class Interactions
- An example is provided where Class B wants to use Class A. Class B can create an instance of Class A and call its methods.
- The speaker emphasizes that programming cannot be reduced to merely creating objects; there’s a need for proper configuration before usage.
Accessing User Information
- To access specific user information (like account details), the application must retrieve the current session or user object.
- The challenge arises when trying to instantiate these objects directly due to unknown parameters required by their constructors.
Role of Service Locator
- The service locator pattern is introduced as a solution for obtaining configured instances without direct instantiation.
- A service locator can return instances and manage their setup, allowing classes to request dependencies without knowing how they are created.
Initialization Process
- There exists an initialization script that creates the first object in the system, which then sets up other necessary components.
- This process often involves retrieving user data from external sources (e.g., GET parameters).
Dependency Management via Service Locator
- Classes like B depend on the service locator for accessing instances of other classes (like A).
- However, this introduces tight coupling between class B and the service locator, which raises concerns about maintainability.
Critique of Service Locator Pattern
Issues with Tight Coupling
- The main criticism against the service locator pattern is that it creates strong dependencies within your codebase.
- If class B relies on the service locator, it becomes difficult to reuse or test independently outside its original context.
Conclusion on Dependency Management Patterns
- Ultimately, while service locators provide convenience in managing dependencies, they also lead to complications in code portability and testing due to their inherent coupling.