PDA

View Full Version : Dependency Injection vs. Service Location


Tom Whitner
10-20-2004, 03:15 PM
Most people should be familiar with Fowler's article regaring this comparison. If not, please look at http://martinfowler.com/articles/injection.html. In his article, Fowler presents the MovieLister/MovieFinder example that Spring.NET implemented as its example. As I examined this example, I was bothered by the following few lines of code.

IApplicationContext ctx = ConfigurationSettings.GetConfig("objects") as IApplicationContext;
MovieLister lister = (MovieLister) ctx.GetObject("MyMovieLister");
Movie[] movies = lister.MoviesDirectedBy("Roberto Benigni");


As I look at this code, I see the use of a Service Locator. My first question is whether that is correct or not. Does the call to ctx.GetObject() qualify as Service Location or not? If so, it seems to me that any Dependency Injection must rely on Service Location to initiate it. I'd like to hear other people oppinion in this.

Thanks,
Tom

choyrim
10-22-2004, 05:05 AM
Does the call to ctx.GetObject() qualify as Service Location or not? If so, it seems to me that any Dependency Injection must rely on Service Location to initiate it.

Yes, the call to ctx.GetObject() is service location. DEPENDENCY INJECTION does not require SERVICE LOCATION to initiate it. But it tends to be much clearer if it is initiated via SERVICE LOCATION.

The container could start in a non-background thread all objects that were marked with a particular interface or attribute. No need for SERVICE LOCATION. But that sort of "magic" tends to confuse coders unfamiliar with the territory. So typically the startup thread pulls out root objects using SERVICE LOCATION.

Let's not forget that both are viable approaches to dealing with service dependencies. DNS is a form of SERVICE LOCATION and it's great. Having your clients injected with their server IP's through some third party system like remote installation services is done sometimes though unwise. Often a combination of the two is the optimal solution.

Just because you're using Spring.NET doesn't mean you have to apply DEPENDENCY INJECTION to everything.

--Choy

Mark Pollack
10-22-2004, 02:35 PM
Hi,


Rod and Jurgen's "J2EE Development without EJB", gives as good an explanation to all the various pros and cons as you will find right now regarding the various issues we are discussing here. Chapter 6 - Lightweight Containers and IoC and Chapter 7 - Introducing the Spring framework are not particularly Java specific and will probably help clarify some of the finer points.

Cheers,
Mark