Dependency Injection in Blazor

By Syncfusion®, Inc. · Last updated

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 you will learn

  • Explain dependencies, injection and the DI container
  • Register a class in Program.cs and ask for its interface
  • Inject with @inject, [Inject] and constructors
  • Use the built-in NavigationManager service

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.

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.

Menu.razor "I need ITeaMenu" Masala, Ginger, Lemon

DI container

ITeaMenu → TeaMenu

NavigationManager

IJSRuntime

asks hands over a TeaMenu

The component asks. The DI container makes the object and hands it over.

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.

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.

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.

Without DI

Menu.razor: new TeaMenu()

Order.razor: new TeaMenu()

Bill.razor: new TeaMenu() change it in 3 places With DI

Menu.razor

Order.razor

Bill.razor

Program.cs ITeaMenu → TeaMenu

change it in 1 place

Without DI, every page makes its own object. With DI, one registration covers every page.

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.

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:
Built-in dependencyWhat it does
NavigationManagerKnows the page address and moves between pages
IJSRuntimeCalls JavaScript (see JavaScript Interop)
ILogger<T>Writes log messages
IConfigurationReads settings from appsettings.json (on the server)

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.)

[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.

  • = 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.

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

MistakeWrong ideaCorrect ideaWhat goes wrong
new TeaMenu() in every pageEach page should make its own objectRegister it once and inject itChanging the menu means editing every page
Injecting a class that is not registeredBlazor finds any class by itselfRegister it in Program.cs"There is no registered service of type ..."
Registering ITeaMenu but asking for TeaMenuThe container matches either oneAsk for the exact type you registered"There is no registered service of type TeaMenu"
[Inject] on a field: [Inject] NavigationManager nav;Any member worksUse a property: { get; set; }The value stays empty (null)
@inject in a plain C# class@inject works everywhereUse constructor injectionA build error
Using an @inject value inside the component's constructorInjected properties are ready in the constructorThey are set after it. Use them in OnInitializedA null value error

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).