I have been seeding my database by using this link
Now when seeding I also would like to access UserManager<ApplicationUser>
and RoleManager<IdentityRole>
.
However, as this is called in the configure method I cannot find the service using;
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
How would I access this inject this in so I can seed my roles etc?
Just to give you a tip, I use this in our Startup.cs. I hope this might help you.
// 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
You also need to inherit this IdentityDbContext<ApplicationUser>
in your DbContext. Like the sample code below:
public class ProjectDbContext : IdentityDbContext<ApplicationUser>
In implementing this in your controller, I would suggest that you use Dependency Injection similar to the code below:
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.