C
C#2y ago
populus

❔ Implementing RoleStore/RoleManager

Hey, I'm dealing with roles for my 2nd time ever and I can't seem to figure this out.
System.NullReferenceException: 'Object reference not set to an instance of an object.'

roleStore was null.
System.NullReferenceException: 'Object reference not set to an instance of an object.'

roleStore was null.
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<ApplicationDbContext>();
UserManager<Account>? userManager = services.GetService<UserManager<Account>>();
var roleStore = services.GetService<RoleStore<IdentityRole>>();
var roleManager = services.GetService<RoleManager<Account>>();

// Create my user.
var user = new Account { UserName = "foo", Email = "foo" };
var password = "foo";
await userManager.CreateAsync(user, password);

// Create role(s).
var rolea = new IdentityRole { Name = "Blogger" };
var roleb = new IdentityRole { Name = "Discusser" };
var rolec = new IdentityRole { Name = "Planner" };

// Insert role(s) into "RoleStore".
var roleTasks = new Task[] {
roleStore.CreateAsync(rolea),
roleStore.CreateAsync(roleb),
roleStore.CreateAsync(rolec)
};
await Task.WhenAll(roleTasks);

// Assign the role(s) to my user.
await userManager.AddToRoleAsync(user, "Blogger");
await userManager.AddToRoleAsync(user, "Discusser");
await userManager.AddToRoleAsync(user, "Planner");
}
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<ApplicationDbContext>();
UserManager<Account>? userManager = services.GetService<UserManager<Account>>();
var roleStore = services.GetService<RoleStore<IdentityRole>>();
var roleManager = services.GetService<RoleManager<Account>>();

// Create my user.
var user = new Account { UserName = "foo", Email = "foo" };
var password = "foo";
await userManager.CreateAsync(user, password);

// Create role(s).
var rolea = new IdentityRole { Name = "Blogger" };
var roleb = new IdentityRole { Name = "Discusser" };
var rolec = new IdentityRole { Name = "Planner" };

// Insert role(s) into "RoleStore".
var roleTasks = new Task[] {
roleStore.CreateAsync(rolea),
roleStore.CreateAsync(roleb),
roleStore.CreateAsync(rolec)
};
await Task.WhenAll(roleTasks);

// Assign the role(s) to my user.
await userManager.AddToRoleAsync(user, "Blogger");
await userManager.AddToRoleAsync(user, "Discusser");
await userManager.AddToRoleAsync(user, "Planner");
}
Secondly if I implement the following code I get a massive error when trying to build the builder.
//builder.Services.AddScoped<IRoleStore<IdentityRole>, RoleStore<IdentityRole>>();
//builder.Services.AddScoped<IRoleStore<IdentityRole>, RoleStore<IdentityRole>>();
1 Reply
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.