What is Dependency injection (DI)?

Dependency injection is when one part of a system gives another part exactly what it needs to work, instead of that part having to find it on its own.

Imagine you're building a sandwich. Normally, the bread has to go out and get the peanut butter by itself, that’s hard work! But with dependency injection, someone else brings the peanut butter straight to the bread. The bread just needs to know where to put it, no running around needed!

How It Works in Real Life

Think of a robot who wants to clean your room. Instead of the robot having to find its own vacuum cleaner, you give it one when you turn it on. That’s dependency injection, you're giving it what it needs right at the start.

Why It's Useful

Without dependency injection, parts of a system have to search for what they need, like the bread searching for peanut butter. With it, everything gets what it needs quickly and clearly. This makes things easier to fix or change later, just like how you can swap out one type of peanut butter for another without changing the bread!

Take the quiz →

Examples

  1. Imagine you're building a robot. Instead of hardwiring the robot's brain to its sensors, you plug them together, making it easier to swap brains or sensors later.
  2. It’s like having a coffee machine that can use any type of coffee bean, you don’t have to change the whole machine just for a new bean.
  3. A chef who uses pre-made sauces instead of cooking everything from scratch, saving time and making dishes more interchangeable.

Ask a question

See also

Discussion

Recent activity