Skip to content

Module 4: Dependency Injection (The Coffee Shop)

📚 Module 4: Dependency Injection

Course ID: DOTNET-102
Subject: The Coffee Shop Principle

In modern .NET, we don’t build our own tools. We ask the System to provide them. This is called Inversion of Control (IoC).


🏗️ Step 1: The “Manual” Problem

Imagine you are a Barista. To make a Latte, you need an Espresso Machine.

  • Bad way (Hardcoding): You build the entire machine from scratch inside your shop every morning. If the machine breaks, you have to close the whole shop to fix it.

🏗️ Step 2: The Service Provider (The “Owner”)

In .NET, the Service Provider acts like the shop owner.

  1. Register: You tell the owner: “I have a great Espresso Machine!” (AddSingleton<IEspressoMachine, Machine>()).
  2. Resolve: When the Barista starts their shift, the owner just hands them the machine.

🧩 The Analogy: Asking for a Pen

  • You don’t manufacture a pen every time you want to write.
  • You just ask: “Hey, does anyone have a pen?”
  • The Dependency Injection Container hands you one.

In Code:

public class Barista {
    private readonly IEspressoMachine _machine;

    // We ASK for the machine in the Constructor
    public Barista(IEspressoMachine machine) {
        _machine = machine;
    }

    public void MakeLatte() => _machine.Brew();
}

🏗️ Step 3: Service Lifetimes

Not all tools are shared the same way:

  1. Singleton: One machine for the whole shop (Shared by everyone).
  2. Scoped: One machine per customer (Thrown away after the order is done).
  3. Transient: A new machine every single time someone asks.

🥅 Module 4 Review

  1. DI: Asking for what you need instead of using new.
  2. Interface: Defining the contract (What the machine does).
  3. Container: The manager that holds all your tools.