Simplest explanation of how a DI container works?

后端 未结 3 621
甜味超标
甜味超标 2021-02-07 20:35

In simple terms and/or in high-level pseudo-code, how does a DI container work and how is it used?

3条回答
  •  旧时难觅i
    2021-02-07 21:34

    "It's nothing more than a fancy hash table of objects."

    While the above is a massive understatement that's the easy way of thinking about them. Given the collection, if you ask for the same instance of an class - the DI container will decide whether to give you a cached version or a new one, or so on.

    Their usage makes it easier and cleaner when it comes to wiring up dependencies. Imagine you have the following pseudo classes.

    class House(Kitchen, Bedroom)
         // Use kitchen and bedroom.
    end
    
    class Kitchen()
        // Code...
    end
    
    class Bedroom()
       // Code...
    end
    

    Constructing a house is a pain without a DI container, you would need to create an instance of a bedroom, followed by an instance of a kitchen. If those objects had dependencies too, you would need to wire them up. In turn, you can spend many lines of code just wiring up objects. Only then could you create a valid house. Using a DI/IOC (Inversion of Control) container you say you want a house object, the DI container will recursively create each of its dependencies and return you a house.

    Without DI/IOC Container:

    house = new House(new Kitchen(), new Bedroom());
    

    With DI/IOC Container:

    house = // some method of getting the house
    

    At the end of the day they make code easy to follow, easier to write and shift the responsibility of wiring objects together away from the problem at hand.

提交回复
热议问题