Lesson 8 of 10

Dependency Injection and Application Services

Create a service, register it in Program.cs, and inject it into Razor components using dependency injection.

Visual Studio 2026.NET 10Beginner friendly

Dependency injection (DI) helps keep UI code separate from application logic. Instead of putting all data operations directly in a page, create a service and ask Blazor to provide it where needed.

1. Create StudentService.cs

Create a folder named Services and add:

namespace BlazorTutorialApp.Services;

public class StudentService
{
    private readonly List<StudentRecord> students = new()
    {
        new StudentRecord(1, "Alice Tan", "Computer Science"),
        new StudentRecord(2, "John Lee", "Software Engineering")
    };

    public IReadOnlyList<StudentRecord> GetStudents()
    {
        return students;
    }

    public void AddStudent(string name, string course)
    {
        int nextId = students.Count == 0 ? 1 : students.Max(s => s.Id) + 1;
        students.Add(new StudentRecord(nextId, name, course));
    }
}

public record StudentRecord(int Id, string Name, string Course);

2. Register the service

In Program.cs, before builder.Build(), add:

builder.Services.AddScoped<StudentService>();

Also add the namespace import at the top if required:

using BlazorTutorialApp.Services;

3. Inject the service into a page

@page "/service-demo"
@using BlazorTutorialApp.Services
@inject StudentService StudentService

<h1>Students from a Service</h1>

<ul>
    @foreach (var student in StudentService.GetStudents())
    {
        <li>@student.Name - @student.Course</li>
    }
</ul>

4. Why use a service?

  • Pages stay focused on presentation and interaction.
  • Data access logic becomes reusable.
  • Services can later use databases, APIs, logging, caching, or other infrastructure.
  • Dependencies are visible and easier to test.
About the demo data

The in-memory list is intentionally simple. It is not a database and isn't suitable for permanent storage. Later you can replace it with Entity Framework Core or an API.

Try it yourself

Add a FindById(int id) method to StudentService that returns the matching student or null.