我正在尝试初始化 Blazor 应用程序的角色。这是我的服务,如果角色不存在,应该创建角色:
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;
}
}
这是program.cs中的服务注册
builder.Services.AddScoped<RoleInitializerService>();
我在服务的
StartAsync
方法中放置了一个断点,但该方法从未执行过。
我做错了什么?问题在于生命周期不匹配还是其他什么?
你可以尝试这个代码:
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Hosting;
using System.Threading;
using System.Threading.Tasks;
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;
}
}
程序.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Register RoleManager and Identity services
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Register the RoleInitializerService as a hosted service
builder.Services.AddHostedService<RoleInitializerService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();