# Dependency Injection

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: Data Access
Source: https://www.devtutorials.ai/learn/blazor/data-access/dependency-injection

> Dependency injection in Blazor: dependencies and injection, what the DI container is and why it is used, registering in Program.cs, built-in dependencies, and @inject, [Inject] and constructor injection with NavigationManager.

## What is Dependency Injection?

First, two short words:

- A **class** is a plan for an object, like `TeaMenu`. An **object** is one real copy made from that plan with `new`.

Now the idea:

- A component often needs an object from another class. For example, the Menu page needs a `TeaMenu` object to get the teas.
- Without help, every component makes that object itself with `new TeaMenu()`.
- With **Dependency Injection (DI)**, the component just **asks** for it. Blazor makes the object and **hands it over**.
- So the component does not care how the object is made, and one line in `Program.cs` can swap it for another.

**Real-World Example:**

- Ravi's Menu, Order and Bill pages all need the list of teas.
- Today the list is written in code. Next month it will come from a database.
- With DI, Ravi changes **one line** in `Program.cs`, and all three pages use the new list. The pages do not change.

<figure className="blz-fig">
<svg viewBox="0 0 640 190" role="img" aria-labelledby="fig-di-ask">
  <title id="fig-di-ask">Animation: Menu.razor says I need ITeaMenu. The request goes to the DI container, a box with shelves. The container picks TeaMenu and hands it back to Menu.razor, which then shows the teas.</title>
  <defs><marker id="fig-di-ask-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="20" y="50" width="180" height="90" rx="12" />
  <text className="t m" x="110" y="78" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Menu.razor</text>
  <text className="t" x="110" y="104" textAnchor="middle" style={{ fontSize: 11 }}>"I need ITeaMenu"<animate attributeName="opacity" values="1;1;0;0" keyTimes="0;0.6;0.65;1" dur="5s" repeatCount="indefinite" /></text>
  <text className="t" x="110" y="104" textAnchor="middle" style={{ fontSize: 11 }} opacity="0">Masala, Ginger, Lemon<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.6;0.65;1" dur="5s" repeatCount="indefinite" /></text>
  <rect className="pur" x="420" y="30" width="200" height="130" rx="12" />
  <text className="t m" x="520" y="54" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>DI container</text>
  <rect className="box" x="440" y="66" width="160" height="26" rx="5" />
  <text className="t m" x="520" y="84" textAnchor="middle" style={{ fontSize: 11 }}>ITeaMenu → TeaMenu</text>
  <rect className="box" x="440" y="98" width="160" height="26" rx="5" />
  <text className="t m" x="520" y="116" textAnchor="middle" style={{ fontSize: 11 }}>NavigationManager</text>
  <rect className="box" x="440" y="130" width="160" height="22" rx="5" />
  <text className="t m" x="520" y="146" textAnchor="middle" style={{ fontSize: 10 }}>IJSRuntime</text>
  <path className="line" d="M200 80 H416" markerEnd="url(#fig-di-ask-a)" />
  <path className="line" d="M420 115 H204" markerEnd="url(#fig-di-ask-a)" />
  <text className="t" x="308" y="72" textAnchor="middle" style={{ fontSize: 11 }}>asks</text>
  <text className="t" x="308" y="134" textAnchor="middle" style={{ fontSize: 11 }}>hands over a TeaMenu</text>
  <circle r="7" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="200;416;416;204;204" keyTimes="0;0.3;0.35;0.6;1" dur="5s" repeatCount="indefinite" />
    <animate attributeName="cy" values="80;80;115;115;115" keyTimes="0;0.3;0.35;0.6;1" dur="5s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>The component asks. The DI container makes the object and hands it over.</figcaption>
</figure>

## Explaining Terms

### Dependencies

- A **dependency** is another class that your component needs to do its job.
- `Menu.razor` needs a `TeaMenu` object to show the teas. So `TeaMenu` is a dependency of `Menu.razor`.
- When a component makes its dependency itself with `new`, the two are **tightly joined**. To change the list, you must edit every page.

In the below example, `Menu.razor` makes its own `TeaMenu` with `new`. It works, but this is the code DI will improve.

@foreach (var tea in menu.GetTeas())
{
      <p>@tea</p>
}

@code {
      // The page makes its own dependency
      private TeaMenu menu = new TeaMenu();
}
`,
    "Models/TeaMenu.cs": `namespace BlazorApp.Models;

public interface ITeaMenu
{
      List<string> GetTeas();
}

public class TeaMenu : ITeaMenu
{
      public List<string> GetTeas() => new() { "Masala Tea", "Ginger Tea", "Lemon Tea" };
}
`,
  }}
/>

### Injection

- **Injection** means the dependency is **given** to the component from outside, instead of being made inside it with `new`.
- Think of a chef: the restaurant gives the chef a stove. The chef does not build one.
- To make swapping easy, the component asks for an **interface**. An **interface** is a list of methods a class promises to have. `ITeaMenu` promises `GetTeas()`.
- Any class that keeps the promise, like `TeaMenu` or `TestTeaMenu`, can be handed in.

<figure className="blz-fig">
<svg viewBox="0 0 640 190" role="img" aria-labelledby="fig-di-before">
  <title id="fig-di-before">Two panels. Without DI: Menu.razor, Order.razor and Bill.razor each have new TeaMenu() inside them. With DI: the three pages each have an arrow from one shared box, Program.cs registers ITeaMenu as TeaMenu.</title>
  <defs><marker id="fig-di-before-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <text className="t m" x="20" y="22" style={{ fontSize: 12, fontWeight: 700 }}>Without DI</text>
  <rect className="box" x="20" y="34" width="270" height="34" rx="6" />
  <text className="t m" x="30" y="56" style={{ fontSize: 11 }}>Menu.razor: new TeaMenu()</text>
  <rect className="box" x="20" y="76" width="270" height="34" rx="6" />
  <text className="t m" x="30" y="98" style={{ fontSize: 11 }}>Order.razor: new TeaMenu()</text>
  <rect className="box" x="20" y="118" width="270" height="34" rx="6" />
  <text className="t m" x="30" y="140" style={{ fontSize: 11 }}>Bill.razor: new TeaMenu()</text>
  <text className="t" x="155" y="176" textAnchor="middle" style={{ fontSize: 11, fill: "#dc2626" }}>change it in 3 places</text>
  <text className="t m" x="340" y="22" style={{ fontSize: 12, fontWeight: 700 }}>With DI</text>
  <rect className="blu" x="340" y="34" width="120" height="34" rx="6" />
  <text className="t m" x="400" y="56" textAnchor="middle" style={{ fontSize: 11 }}>Menu.razor</text>
  <rect className="blu" x="340" y="76" width="120" height="34" rx="6" />
  <text className="t m" x="400" y="98" textAnchor="middle" style={{ fontSize: 11 }}>Order.razor</text>
  <rect className="blu" x="340" y="118" width="120" height="34" rx="6" />
  <text className="t m" x="400" y="140" textAnchor="middle" style={{ fontSize: 11 }}>Bill.razor</text>
  <rect className="pur" x="500" y="66" width="125" height="54" rx="8" />
  <text className="t m" x="562" y="88" textAnchor="middle" style={{ fontSize: 11 }}>Program.cs</text>
  <text className="t m" x="562" y="106" textAnchor="middle" style={{ fontSize: 10 }}>ITeaMenu → TeaMenu</text>
  <path className="line" d="M500 80 L464 51" markerEnd="url(#fig-di-before-a)" />
  <path className="line" d="M500 93 H464" markerEnd="url(#fig-di-before-a)" />
  <path className="line" d="M500 106 L464 135" markerEnd="url(#fig-di-before-a)" />
  <text className="t" x="482" y="176" textAnchor="middle" style={{ fontSize: 11, fill: "#16a34a" }}>change it in 1 place</text>
</svg>
<figcaption>Without DI, every page makes its own object. With DI, one registration covers every page.</figcaption>
</figure>

## DI Container

**What it is**

- The **DI container** is a helper inside Blazor. It keeps a list of classes, and makes an object from that list when a component asks for one.
- Think of the tea shop's storeroom: the chef asks for a kettle, and the storeroom keeper hands one over. The chef never builds a kettle.

**Why it is used**

- Components never write `new` for their dependencies. They only ask.
- The list lives in one place, `Program.cs`. Change one line there, and every component gets the new class.
- If a class needs another class to work, the container makes that one too and passes it in.
- You never build the container yourself. Blazor makes it when the app starts.

The container is like the storeroom keeper: you say **what** you need, and it decides **how** to get it.

## Registering Dependencies

- **Registering** means adding a class to the container's list. You do it once, in `Program.cs`, before `builder.Build()`.
- Write the interface first and the class second. The line below means: "when someone asks for `ITeaMenu`, give them a `TeaMenu`".
- Here the dependency is registered with `AddScoped`.

`AddScoped` decides how long one object lives. You don't need to worry about this now. We will learn it in a later lesson.

The code boxes cannot edit `Program.cs`, so the box below makes the same list in code with `ServiceCollection`. In the below example, the list maps `ITeaMenu` to `TeaMenu`. Change `TeaMenu` to `TestTeaMenu` on the marked line and press **Run**: the page shows the test list, and nothing else changes.

}

@code {
      private List<string> teas = new();

      protected override void OnInitialized()
      {
          var services = new ServiceCollection();
          services.AddScoped<ITeaMenu, TeaMenu>(); // swap to TestTeaMenu
          var container = services.BuildServiceProvider();

          teas = container.GetRequiredService<ITeaMenu>().GetTeas();
      }
}
`,
    "Models/TeaMenu.cs": `namespace BlazorApp.Models;

public interface ITeaMenu
{
      List<string> GetTeas();
}

public class TeaMenu : ITeaMenu
{
      public List<string> GetTeas() => new() { "Masala Tea", "Ginger Tea", "Lemon Tea" };
}

public class TestTeaMenu : ITeaMenu
{
      public List<string> GetTeas() => new() { "Test Tea" };
}
`,
  }}
/>

If you forget to register a class, the page fails with an error like "There is no registered service of type ITeaMenu". Check `Program.cs` first.

**Built-in dependencies**

- Blazor also registers many classes for you, so you can ask for them with no extra line. These are its **built-in services**.
- The default lines in a new project's `Program.cs` add them:

<div className="tscroll">

| Built-in dependency | What it does |
|---|---|
| `NavigationManager` | Knows the page address and moves between pages |
| `IJSRuntime` | Calls JavaScript (see **JavaScript Interop**) |
| `ILogger<T>` | Writes log messages |
| `IConfiguration` | Reads settings from `appsettings.json` (on the server) |

</div>

## Injecting Dependencies

- **Injecting** means getting a registered object into a component. There are three ways: `@inject`, `[Inject]` and a constructor.
- The examples use the built-in `NavigationManager`, so the code boxes need no change to `Program.cs`. Your own classes, like `ITeaMenu`, work the same way.

**Meet NavigationManager**

- `NavigationManager` knows the address of the current page and can move to another page.
- `Uri` is the full address of the page. `BaseUri` is the start of the site.
- `GetUriWithQueryParameter("tea", "masala")` builds an address that ends with `?tea=masala`.
- `NavigateTo("/order")` moves to another page from C#, for example after an order is saved.

### @inject

- Write `@inject` at the top of a `.razor` file: the type, then a name for it.
- `@inject ITeaMenu Menu` gives the component a property called `Menu`.

}
`}
/>

In the below example, `@inject NavigationManager Nav` gives the page Blazor's `NavigationManager`. The page shows its address and builds a link to the order page. (It does not move there, so you stay on this lesson.)

<p>Order link: @orderLink</p>

@code {
      private string orderLink = "";

      protected override void OnInitialized()
      {
          orderLink = Nav.GetUriWithQueryParameter("tea", "masala");
      }
}
`,
  }}
/>

### [Inject]

- `[Inject]` does the same job from C# code: put it on a **property** in `@code`.

In the below example, the `[Inject]` property `Nav` is filled by Blazor before the component starts.

@code {
      [Inject]
      private NavigationManager Nav { get; set; } = default!;
}
`,
  }}
/>

- `= default!` tells C# "this will be filled in later", so it does not warn about a missing value.
- In your own app, `BaseUri` is the start of the site, like `https://localhost:7090/`. In the code box, it shows this lesson's folder.

### Constructor Injection

- A **constructor** is a special method that runs when an object is made. It has the same name as the class.
- Since .NET 9, a component can get its dependencies through its constructor. This is also the normal way for plain C# classes, like an `OrderChecker` that needs `ITeaMenu`.

In the below example, `Home`'s constructor receives `NavigationManager` and keeps it in a field.

@code {
      private readonly NavigationManager nav;
      private string path = "";

      public Home(NavigationManager nav)
      {
          this.nav = nav;
      }

      protected override void OnInitialized()
      {
          path = nav.ToBaseRelativePath(nav.Uri);
      }
}
`,
  }}
/>

Plain C# classes use constructor injection too:

`@inject` and `[Inject]` work only in components. In a plain C# class, always use a constructor.

## Common mistakes

<div className="tscroll">

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `new TeaMenu()` in every page | Each page should make its own object | Register it once and inject it | Changing the menu means editing every page |
| Injecting a class that is not registered | Blazor finds any class by itself | Register it in `Program.cs` | "There is no registered service of type ..." |
| Registering `ITeaMenu` but asking for `TeaMenu` | The container matches either one | Ask for the exact type you registered | "There is no registered service of type TeaMenu" |
| `[Inject]` on a field: `[Inject] NavigationManager nav;` | Any member works | Use a property: `{ get; set; }` | The value stays empty (null) |
| `@inject` in a plain C# class | `@inject` works everywhere | Use constructor injection | A build error |
| Using an `@inject` value inside the component's constructor | Injected properties are ready in the constructor | They are set after it. Use them in `OnInitialized` | A null value error |

</div>

## Check Yourself

## Exercises

## What to Remember

- A dependency is another class your component needs. Injection means its object is given to you, not made with `new`.
- The DI container keeps a list of classes and makes their objects when asked. Components only ask, and never write `new`.
- Register in `Program.cs`, for example `builder.Services.AddScoped<ITeaMenu, TeaMenu>();`. Ask for the interface, so the class can be swapped.
- Inject with `@inject Type Name`, with `[Inject]` on a property, or through a constructor. Plain C# classes use constructors.
- Built-in dependencies, like `NavigationManager` and `IJSRuntime`, are added by the default lines in `Program.cs`.
- `NavigationManager` knows the address (`Uri`, `BaseUri`), builds links (`GetUriWithQueryParameter`) and moves pages (`NavigateTo`).
