Dependency Injection vs Service Location

前端 未结 11 1376
梦如初夏
梦如初夏 2020-11-28 03:59

I am currently weighing up the advantages and disadvantages between DI and SL. However, I have found myself in the following catch 22 which implies that I should just use SL

11条回答
  •  旧巷少年郎
    2020-11-28 04:52

    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();
    }
    

    Wrong:

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

    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.

提交回复
热议问题