我一直在使用这个链接来播种我的数据库。
现在,在播种时,我还想访问UserManager<ApplicationUser>和RoleManager<IdentityRole>。
但是,由于这是在配置方法中调用的,所以我无法使用;
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
我将如何访问这个注入,以便我可以种子我的角色,等等?
发布于 2018-03-20 10:30:16
为了给你一个提示,我在我们的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>在您的控制器中实现此功能时,我建议您使用类似于下面代码的依赖注入:
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);
}https://stackoverflow.com/questions/49381335
复制相似问题