RoleManager.FindByNameAsync throws a NullReferenceException

In my Startup.csfile, in a method Configure, I'm trying to sow some roles.
I insert IServiceScopeFactoryin 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 FindByNameAsyncthrows an exception, although it is FindByNameAsyncdeclared as an instance variable. The same exception occurs when called RoleExistsAsync.

What am I missing?

+4
source share

Source: https://habr.com/ru/post/1692577/


All Articles