In my Startup.cs
file, in a method Configure
, I'm trying to sow some roles.
I insert IServiceScopeFactory
in a method call:
RoleSeeder(app.ApplicationServices.GetRequiredService<IServiceScopeFactory>());
in this method, I create a new object (of course, with a factory scope) and call the method on it Seed
:
public void Seed(ApplicationDbContext context)
{
using(var scope = scopeFactory.CreateScope())
{
roleManager = scope.ServiceProvider.GetService<RoleManager<IdentityRole>>();
CreateRoleIfNotExists("Finance");
CreateRoleIfNotExists("Admin");
}
}
Method CreateRoleIfNotExists
:
private async void CreateRoleIfNotExists(string role)
{
var roles = roleManager.Roles;
if (await roleManager.FindByNameAsync(role) == null)
{
await roleManager.CreateAsync(new IdentityRole { Name = role });
}
}
The method FindByNameAsync
throws an exception, although it is FindByNameAsync
declared as an instance variable. The same exception occurs when called RoleExistsAsync
.
What am I missing?
source
share