Constructor Injection - Do we inject factories as well?

前端 未结 2 1575
猫巷女王i
猫巷女王i 2021-02-15 07:12

After listening to the Clean Code Talks, I came to understand that we should use factories to compose objects. So, for example, if a House has a Door a

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-15 07:32

    Staying with the Door and DoorKnob example, you don't inject a factory - you inject the DooKnob itself:

    public class Door
    {
        private readonly DoorKnob doorKnob;
    
        public Door(DoorKnob doorKnob)
        {
            if (doorKnob == null)
                throw new ArgumentNullException("doorKnob");
    
            this.doorKnob = doorKnob;
        }
    }
    

    No factories are in sight in this level.

    House, on the other hand, depends on Door, but not on DoorKnob:

    public class House
    {
        private readonly Door door;
    
        public House(Door door)
        {
            if (door == null)
                throw new ArgumentNullException("door");
    
            this.door = door;
        }
    }
    

    This keeps options open until at last you have to compose everything in the application's Composition Root:

    var house = new House(new Door(new DoorKnob()));
    

    You can use a DI Container to compose at this level, but you don't have to. No factories are involved.

提交回复
热议问题