What are the benefits of dependency injection containers?

前端 未结 16 2741
南笙
南笙 2020-12-02 04:09

I understand benefits of dependency injection itself. Let\'s take Spring for instance. I also understand benefits of other Spring featureslike AOP, helpers of different kind

16条回答
  •  一整个雨季
    2020-12-02 04:45

    Your case is very simple and therefore doesn't need an IoC (Inversion of Control) container like Spring. On the other hand, when you "program to interfaces, not implementations" (which is a good practice in OOP), you can have code like this:

    IService myService;
    // ...
    public void doSomething() {
      myService.fetchData();
    }
    

    (note that the type of myService is IService -- an interface, not a concrete implementation). Now it can be handy to let your IoC container automatically provide the correct concrete instance of IService during initialization - when you have many interfaces and many implementations, it can be cumbersome to do that by hand. Main benefits of an IoC container (dependency injection framework) are:

    • External configuration of mapping between interfaces and their concrete implementations
    • IoC container handles some tricky issues like resolving complicated dependency graphs, managing component's lifetime etc.
    • You save coding time because you provide mappings declaratively, not in a procedural code
    • Inversion of Control principle allows for easy unit testing because you can replace real implementations with fake ones (like replacing SQL database with an in-memory one)

提交回复
热议问题