There are two main issues with the design. The first is the design does not implement async/await properly. The second issue is not following the seeding pattern illustrated in one of your previous threads.
The following code sample illustrates how to implement async/await, create services, and seed data when the application starts. The example uses Sqlite and default Identity.
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using MvcIdentity.Data;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
await SeedData.InitializeAsync(services);
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();
The extension method
public static class SeedData
{
public static async Task InitializeAsync(IServiceProvider serviceProvider)
{
using (var roleManager = serviceProvider.GetService<RoleManager<IdentityRole>>())
{
if(roleManager != null)
{
if (!(await roleManager.RoleExistsAsync("Admin")))
{
await roleManager.CreateAsync(new IdentityRole("Admin"));
}
if (!(await roleManager.RoleExistsAsync("Manager")))
{
await roleManager.CreateAsync(new IdentityRole("Manager"));
}
}
}
using (var userManager = serviceProvider.GetService<UserManager<IdentityUser>>())
{
if (userManager != null)
{
IdentityUser? user = await userManager.FindByEmailAsync("Info@Admin.com");
if (user == null)
{
var newUser = new IdentityUser()
{
Email = "Info@Admin.com",
UserName = "Info@Admin.com",
EmailConfirmed = true
};
var result = await userManager.CreateAsync(newUser, "@Password123");
if (result.Succeeded)
{
await userManager.AddToRoleAsync(newUser, "Admin");
}
}
else
{
if (!(await userManager.IsInRoleAsync(user, "Admin")))
{
await userManager.AddToRoleAsync(user, "Admin");
}
}
}
}
}
}