gpt4 book ai didi

c# - 在 Asp.Net Core 2 中使用 RoleManager 播种角色

转载 作者:太空宇宙 更新时间:2023-11-03 22:46:59 25 4
gpt4 key购买 nike

我一直在使用此链接为我的数据库做种

Seeding Db with AspNet Core

现在播种时我也想访问 UserManager<ApplicationUser>RoleManager<IdentityRole> .

但是,因为这是在配置方法中调用的,所以我找不到正在使用的服务;

var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

我如何访问这个注入(inject)这个以便我可以播种我的角色等?

最佳答案

只是给你一个提示,我在我们的 Startup.cs 中使用它。希望这对您有所帮助。

// Inside the public void Configure(IApplicationBuilder app)

var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();

var scope = scopeFactory.CreateScope();

var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();

new UserRoleSeed(roleManager).Seed(); // Where UserRoleSeeding happens

你还需要继承这个IdentityDbContext<ApplicationUser>在你的 DbContext 中。就像下面的示例代码:

public class ProjectDbContext : IdentityDbContext<ApplicationUser>

在您的 Controller 中实现它时,我建议您使用类似于以下代码的依赖注入(inject):

private readonly UserManager<ApplicationUser> userManager;
private readonly RoleManager<IdentityRole> roleManager;

public TestingController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager){
this.userManager = userManager;
this.roleManager = roleManager;
}

public async Task<IActionResult> Index(){
// Test in getting userManager
var user = await userManager.GetUserAsync(HttpContext.User);
}

关于c# - 在 Asp.Net Core 2 中使用 RoleManager 播种角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49381335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com