Sobes.tech
Junior — Middle

What is the difference between the Service Locator approach and Dependency Injection in managing dependencies in an application?

sobes.tech AI

Answer from AI

Service Locator and Dependency Injection (DI) are two patterns for managing dependencies, but they differ in how they provide dependencies.

Service Locator:

  • A component requests dependencies from a centralized service (locator).
  • The locator hides the creation and configuration of dependencies.
  • The component code explicitly calls the locator to obtain the required service.
  • Leads to tighter coupling and complicates testing, as dependencies are requested inside the class.

Dependency Injection:

  • Dependencies are passed into the class from outside (via constructor, setter, or interface).
  • The class does not know where dependencies come from; it simply uses them.
  • Improves testability and modularity, as dependencies can be easily replaced.

Example of DI in Kotlin:

class UserRepository(val apiService: ApiService) {
    fun getUser() = apiService.fetchUser()
}

// Injecting dependency from outside
val apiService = ApiService()
val userRepository = UserRepository(apiService)

In the end, DI is considered a more transparent and flexible approach, while Service Locator is more hidden and less preferred from a clean architecture perspective.

What is the difference between the Service Locator… - sobes.tech