Injecting a Service in a Blazor Partial Class

Why Blazor Partial Class is a better idea

Blazor is a modern web development framework that allows developers to build web applications using .NET and C#. One of the key features of Blazor is its ability to create reusable components using Razor syntax. However, sometimes we need to split our components into multiple files for better organization and maintainability. This is where Blazor partial classes come in. Using Blazor partial classes, we can split our components into multiple files while keeping them logically connected. This makes our code easier to read, understand, and maintain. Additionally, partial classes allow us to unit test our components more effectively, since we can test each part of the component separately.

Injecting a Service in a Blazor Partial Class

One of the key features of Blazor is its ability to handle dependency injection, which allows us to easily inject services into our components. In this blog post, we will explore how to inject a service into a Blazor partial class and demonstrate this with an example that displays a list of students using mock data.

Example: Displaying a List of Students

Let's demonstrate how to inject services with an example.

In this example, we'll create a simple Blazor component that displays a list of students using mock data. We'll inject a StudentService into our component and use it to get the list of students.

First, let's create our StudentService class:

public class StudentService
{
    private readonly List<Student> students = new List<Student>
    {
        new Student { Id = 1, Name = "Alice", Age = 21 },
        new Student { Id = 2, Name = "Bob", Age = 22 },
        new Student { Id = 3, Name = "Charlie", Age = 23 }
    };

    public Task<List<Student>> GetStudentsAsync()
    {
        return Task.FromResult(students);
    }
}

This class contains a list of mock students and a method that returns this list as a Task<List<Student>>. In Razor Pages, we can inject services into our classes by using the @inject directive in our Razor markup or by using the [Inject] attribute in our C# code. The injected service is automatically resolved by the DI container.

Next, let's create our StudentList component:

public partial class StudentList
{
    [Inject]
    private StudentService studentService { get; set; }

    private List<Student> students;

    protected override async Task OnInitializedAsync()
    {
        students = await studentService.GetStudentsAsync();
    }
}

In this component, we're injecting our StudentService using the Inject attribute. We're also overriding the OnInitializedAsync method to get the list of students from our service.

Finally, let's create the Razor markup for our component:

<h1>Student List</h1>

<ul>
    @foreach (var student in students)
    {
        <li>@student.Name, @student.Age</li>
    }
</ul>