How to Inject Services in .NET Code Blazor - Windows ASP.NET Core Hosting 2024 | Review and ComparisonWindows ASP.NET Core Hosting 2024 | Review and Comparison

In .NET Core, we have built in Dependency Injection feature, .NET Core’s Blazor application’s Razor Page also provides feature to use Dependency Injection in the view page, Users can inject services into Razor’s page using @inject keyword followed by name of the service, following steps help you to create Service and know how to inject that service in .NET Core Blazor Server App Razor View Page:

To begin with implementing and using Dependency Injection and injecting Services into Razor View Pages of Blazor Server app, we need to create the app, we can create it with either Visual Studio or using .NET CLI Commands:

1. Use the below .NET CLI command or use Visual Studio “Create New Project

dotnet new blazorserver -o InjectServiceApp

Or Create it using Visual Studio => Create New Project window, select “Blazor Server App” option and click on Next button, specify the Project Name, Location & Solution Name in the fields and click on Next button, In the next window, select the Target Framework & Authentication Type and click on Create button to create the Project

2. Create the IUserService.cs interface and UserService.cs class in Data folder of the project and add below code:

   interface IUserService
   {
       List<string> GetUsers();
       void AddUser(string name);
   }
  public class UserService: IUserService
   {
        private List<string> _users = new List<string>();
        public List<string> GetUsers()
        {
            return _users;
        }

        public void AddUser(string name)
        {
            _users.Add(name);
        }
   }

In the above UserService, we have created it by inhering it from IUserService which has 2 methods GetUsers() and AddUser(string name). We are adding the users into a private variable _users when AddUser(string name) method is called and sending the user list(_users) when GetUsers() method is called.

3. Now we will be Configuring the above UserService in Startup.cs class inside ConfigureServices() method.

  public void ConfigureServices(IServiceCollection services)
  {
      services.AddRazorPages();
      services.AddServerSideBlazor();
      services.AddScoped<IUserService, UserService>();
  }

In the above ConfigureServices() method, we have specified the lifetime of the UserService as Scoped, you can modify it to Singleton or Transient based on your requirement.

4. We are going to use the above UserService in our Razor view page, to use it we have to inject the service using below syntax:

@page "/"
@inject InjectServiceApp.Data.IUserService userService

@if (_users != null)
{
    <ul>
        @foreach (var user in _users)
        {
            <li>@user</li>
        }
    </ul>
}

@code{
    private List<string> _users;
    protected override void OnInitialized()
    {
        userService.AddUser("John");
        userService.AddUser("Brian");
        userService.AddUser("Tom");
        _users = userService.GetUsers();
    }
}

As per above code, we have to inject the Service using @inject keyword and add the service name which we have to inject in the Blazor Application’s Razor View Page. you can see we have used the object of the injected IUserService inside the @code to call the methods of the service. Using above code, you will get output as shown below:

You can try above way of injecting Services into your Blazor application’s Razor View Page. Hope this article helpful for you!