I am trying to initialize roles for my Blazor app. This is my service that should create roles if they don't exist:
using Microsoft.AspNetCore.Identity;
namespace FoodApp.Services
{
public class RoleInitializerService : IHostedService
{
private readonly RoleManager<IdentityRole> _roleManager;
public RoleInitializerService(RoleManager<IdentityRole> roleManager)
{
_roleManager = roleManager;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
string[] roles = { "Administrator", "User" };
foreach (var role in roles)
{
if (!await _roleManager.RoleExistsAsync(role))
{
await _roleManager.CreateAsync(new IdentityRole(role));
}
}
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
}
And this is service registration in program.cs
builder.Services.AddScoped<RoleInitializerService>();
I put a breakpoint inside the StartAsync method of my service, and the method was never executed.
What am I doing wrong? Is the problem laying in lifetime mismatch or what else?