Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service Locator vs. Dependency Injection

I'm reviewing code with a lot of statements like this:

private SomeInterface x = Locator.getInstance(SomeInterface.class)

I would expect something like

private SomeInterface x;

@Inject
public Consumer(SomeInterface x){ // constructor
    this.x = x;
}

Is there something wrong with the first approach? Ok, dependencies are not so obvious, but implementations could easily be swapped through configuration of Locator.

like image 914
deamon Avatar asked Jun 09 '11 10:06

deamon


2 Answers

Martin Fowler wrote an article on DI versus Locators:

For DI:

  • Easier to determine what dependencies a component has - look at constructor.
  • Component does not have dependency on Service Locator so there is not a problem if the component is used with a different framework.
  • DI may make testing easier but a good Service Locator mechanism will make stubbing equally feasible

Against DI:

  • Harder to debug and understand.
  • Component cannot request extra services from injector once it had been configured.

I personally don't think there's anything inherently bad with the first locator based approach - I guess DI does standardise this though, so if it's available I would use it. All good ideas tend to end up as frameworks at some point, so this has what's happened here. Plus with DI you can take advantage of other annotations, scopes, etc. without having to roll your own code. And the less bespoke code your project uses the better IMO. I'll leave the last word to Fowler though:

The choice between Service Locator and Dependency Injection is less important than the principle of separating service configuration from the use of services within an application.

like image 200
planetjones Avatar answered Sep 28 '22 08:09

planetjones


First example : x = Locator.getInstance(SomeInterface.class) is looks like Service Locator pattern, and http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx check this article it says Service Locator is an anti-pattern and should be avoided

And for the second usage its all fine i like Constructor Injection, its smooth fine implementation. But I would like to not to use Attributes ( annotanitons in Java?) cause anytime i might want to change DI container i am using and i dont want to remove an attribute from all classes.

like image 40
adt Avatar answered Sep 28 '22 08:09

adt