What is the difference between a Service Locator and Dependency Injection?
With DI, dependencies are handed to the class from outside. With a Service Locator, the class asks a global registry for them. The locator hides what the class needs and makes testing harder.
Explain it simply
In a hostel, DI is the mess delivering your meal to your room, and the Service Locator is you walking to the kitchen every time to ask for it. The second works, but from your room's door nobody can tell you depend on the kitchen.
Looking at a class's constructor tells you everything it needs under DI. Under a locator, you must read every line of its code.
Example
// Service Locator: hidden dependency
class Invoice {
void send() {
Mailer m = ServiceLocator.get(Mailer.class); // surprise at runtime if missing
m.send("invoice");
}
}
// Dependency Injection: visible dependency
class Invoice2 {
private final Mailer mailer;
Invoice2(Mailer mailer) { this.mailer = mailer; }
void send() { mailer.send("invoice"); }
}A missing registration in the locator version only fails when send() runs. In the DI version, you cannot even create the object without a Mailer.
What to say in the interview
"DI pushes dependencies in, so they appear in the constructor and are easy to fake. A service locator pulls them from a global registry, hiding the dependency and coupling the class to the locator. I prefer DI, and use a locator only at application boundaries if at all."
Common mistakes
- Calling a DI container directly from inside business classes. That turns it into a service locator.