c# - 'Identity.UserManager`1[ProjectName.ApplicationUser]' 类型的服务没有注册。当容器被销毁时可用)'
问题描述
我正在尝试将一些角色和用户添加到我的项目中。我正在使用 ASP.NET Core 3.1 版。现在我在我的 Startup 课程中尝试了这个:
private async Task CreateRoles(IServiceProvider serviceProvider)
{
//initializing custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Admin", "Operacional"};
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
// ensure that the role does not exist
if (!roleExist)
{
//create the roles and seed them to the database:
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
// find the user with the admin email
var _user = await UserManager.FindByEmailAsync("admin@gmail.com");
// check if the user exists
if (_user == null)
{
//Here you could create the super admin who will maintain the web app
var poweruser = new ApplicationUser
{
UserName = "Admin",
Email = "admin@gmail.com",
};
string adminPassword = "Abc*123";
var createPowerUser = await UserManager.CreateAsync(poweruser, adminPassword);
if (createPowerUser.Succeeded)
{
//here we tie the new user to the role
await UserManager.AddToRoleAsync(poweruser, "Admin");
}
}
}
和
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
//SIGNAL R
//String caminho = configuration["AppSettings:Servidor"] + "/myHub";
String caminho = Configuration["AppSettings:Servidor"] + "/myHub";
//endpoints.MapHub<MyHub>(caminho);
//app.UseSignalR(route =>
//{
// route.MapHub<MyHub>(caminho);
//});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<MyHub>("/myHub");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
CreateRoles(serviceProvider).Wait();
}
当我运行该项目时,它在 CreateRoles 中给我错误“System.AggregateException:'No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[ProjectName.ApplicationUser]' has been registered.able when container is destroy)'” (服务提供者).Wait(); 为什么会这样?
解决方案
尝试添加services.AddDefaultIdentity<ApplicationUser>();
您的Startup.cs
.
有关更多信息,您可以查看官方文档。
推荐阅读
- ietf-netmod-yang - 杨建模语言 - 在位类型中选择/取消选择一个或多个选项
- java - 如何使用 simple_list_item_2 布局和两个数组(android studio)?
- css - 悬停在“父链接”下时如何停止下拉菜单?
- apache-spark - 如何在 Glue python 中延迟加载日志消息?
- javascript - DrawFlow - 如何设置每个连接名称和 ID
- javascript - 反应:MouseEvent.target 上的数据集值不一致
- ios - “错误 ITMS-90171:“无效的捆绑结构 - 不允许二进制文件 'School Diary.app/NewEventsCustomTableViewCell.o'”
- r - 成对减去数据表中的列
- python - 在绘图时为列表中的元素分配颜色
- c++ - 我的图书馆程序有问题