Dependency Injection vs Service Location

Because the class is now being injected with an IoC container, then why not use it to resolve all other dependencies too?

Using the service locator pattern completely defeats one of the main points of dependency injection. The point of dependency injection is to make dependencies explicit. Once you hide those dependencies by not making them explicit parameters in a constructor, you’re no longer doing full-fledged dependency injection.

These are all constructors for a class named Foo (set to the theme of the Johnny Cash song):

Wrong:

public Foo() {
    this.bar = new Bar();
}

Wrong:

public Foo() {
    this.bar = ServiceLocator.Resolve<Bar>();
}

Wrong:

public Foo(ServiceLocator locator) {
    this.bar = locator.Resolve<Bar>();
}

Right:

public Foo(Bar bar) {
    this.bar = bar;
}

Only the latter makes the dependency on Bar explicit.

As for logging, there’s a right way to do it without it permeating into your domain code (it shouldn’t but if it does then you use dependency injection period). Amazingly, IoC containers can help with this issue. Start here.

Leave a Comment