[英]How to access UserManager<IdentityUser> instance from WebApplication instance app in program.cs in asp.net core 7.0
I need to access UserManager instance to seed IdentityUser data, I am doing in program.cs file Below is given code snippet我需要访问 UserManager 实例来播种 IdentityUser 数据,我在 program.cs 文件中做下面给出了代码片段
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services
.AddDefaultIdentity<MyIdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>();
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
});
builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();
builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/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.MapControllers();
app.MapControllerRoute(
name: "default",
pattern: "{controller = Home}/{action = Index}/{Id?}"
);
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapDefaultControllerRoute();
app.MapRazorPages();
var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
var scope = scopeFactory.CreateScope();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<MyIdentityUser>>();
SeedInitialData.SeedData(roleManager, userManager);
app.Run();
and I receive this exception我收到这个例外
InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered.
InvalidOperationException:没有注册类型为“Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]”的服务。 Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider 提供者,类型 serviceType)
Please help me, how to find this issue.请帮助我,如何找到这个问题。 regards
问候
I read many articles, and I tried some of them, none of them worked for me.我读了很多文章,我尝试了其中一些,但没有一篇对我有用。
I create a simple demo to show how to seed data to identity in asp.net core, You can refer to it.我创建了一个简单的演示来展示如何在 asp.net 核心中将数据播种到身份,您可以参考它。
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
//.........
builder.Services.AddIdentity<IdentityUser,IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
var app = builder.Build();
// Configure the HTTP request pipeline.
//........
app.UseAuthorization();
using (var scope = app.Services.CreateScope())
{
//Resolve ASP .NET Core Identity with DI help
var userManager = (UserManager<IdentityUser>)scope.ServiceProvider.GetService(typeof(UserManager<IdentityUser>));
var roleManager = (RoleManager<IdentityRole>)scope.ServiceProvider.GetService(typeof(RoleManager<IdentityRole>));
// do you things here
MyIdentityDataInitializer.SeedData(userManager, roleManager);
}
//........
app.Run();
}
}
MyIdentityDataInitializer class我的身份数据初始化器 class
public static class MyIdentityDataInitializer
{
public static void SeedData(UserManager<IdentityUser> userManager,RoleManager<IdentityRole> roleManager)
{
SeedRoles(roleManager);
SeedUsers(userManager);
}
public static void SeedUsers(UserManager<IdentityUser> userManager)
{
if (userManager.FindByNameAsync("user1").Result == null)
{
IdentityUser user = new IdentityUser();
user.UserName = "user1";
user.Email = "user1@localhost";
IdentityResult result = userManager.CreateAsync(user, "Password123!!!").Result;
if (result.Succeeded)
{
userManager.AddToRoleAsync(user,
"NormalUser").Wait();
}
}
if (userManager.FindByNameAsync("user2").Result == null)
{
IdentityUser user = new IdentityUser();
user.UserName = "user2";
user.Email = "user2@localhost";
IdentityResult result = userManager.CreateAsync(user, "Password123!!!").Result;
if (result.Succeeded)
{
userManager.AddToRoleAsync(user,
"Administrator").Wait();
}
}
}
public static void SeedRoles(RoleManager<IdentityRole> roleManager)
{
if (!roleManager.RoleExistsAsync("NormalUser").Result)
{
IdentityRole role = new IdentityRole();
role.Name = "NormalUser";
IdentityResult roleResult = roleManager.CreateAsync(role).Result;
}
if (!roleManager.RoleExistsAsync("Administrator").Result)
{
IdentityRole role = new IdentityRole();
role.Name = "Administrator";
IdentityResult roleResult = roleManager.CreateAsync(role).Result;
}
}
}
Now when I run my project, The data will be seeded successfully.现在当我运行我的项目时,数据将被成功播种。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.