Tuesday, August 14, 2007

Service Locator an alternative to Dependency Injection?

In my unending quest for knowledge, I read an article explaining Dependency Injection as well as discussing Service Locator as an alternative.

After taking some time to talk about each pattern individually (DI & SL), it's finally time address the real question. Is Service Locator an alternative to Dependency Injection?

The most important aspect of DI is IoC (Inversion of Control). Through DI, you pass control to the consumer of the class. For the sake of argument, let's say you decide to implement Service Locator instead of DI. Now a class gets its resources from the ServiceLocator class and is no longer coupled directly to the resource itself. Assuming your primary goal was IoC, who now controls the resource? Well, the SeriveLocator class. So you've passed control from one class to another. Does that accomplish IoC? No. A consumer of your class still has no control. So what do you do? You implement DI to inject the resource into the ServiceLocator; and what were we trying to accomplish by using Service Locator instead of DI in the first place?

When it comes down to it, they only share one thing in common: the ability to decouple a class from its dependencies. While technology independence is a noble cause, these two patterns offer much more.

Look at it this way. Would you ever tell someone that's looking to buy a corvette that a mini van is an alternative? No. Now, if you're only concerned with getting from point A to point B, the mini van would be a viable alternative. But, who buys a corvette just to get from point A to point B ?

Conclusion
DI offers decoupling with the benefit of IoC. Service Locator should be used to manage services for multiple consumers and abstract away the pain of accessing that service.

No comments: