RoleManager.FindByNameAsync 抛出 NullReferenceException

问题描述 投票:0回答:1

在我的

Startup.cs
文件中,在
Configure
方法中,我正在尝试播种一些角色。
我在方法调用中注入
IServiceScopeFactory

RoleSeeder(app.ApplicationServices.GetRequiredService<IServiceScopeFactory>());

在此方法中,我创建一个新对象(当然带有服务范围工厂集)并调用其上的

Seed
方法:

public void Seed(ApplicationDbContext context)
{            
    using(var scope = scopeFactory.CreateScope())
    {
        roleManager = scope.ServiceProvider.GetService<RoleManager<IdentityRole>>();
        CreateRoleIfNotExists("Finance");
        CreateRoleIfNotExists("Admin");
    }
}

CreateRoleIfNotExists
方法:

private async void CreateRoleIfNotExists(string role)
{
    var roles = roleManager.Roles;
    if (await roleManager.FindByNameAsync(role) == null)
    {
        await roleManager.CreateAsync(new IdentityRole { Name = role });
    }
}

尽管

FindByNameAsync
被声明为实例变量,但
FindByNameAsync
方法会引发异常。调用
RoleExistsAsync
时也会引发相同的异常。

我错过了什么?

c# asp.net-core .net-core asp.net-core-identity
1个回答
0
投票

我们还需要从 ServiceProvider 读取范围。下面的代码对我们来说工作正常。

using (var scope = builder.ApplicationServices.CreateScope())
{
    var _userManager = scope.ServiceProvider.GetRequiredService<RoleManager<ApplicationRole>>();
    var hrRole = new ApplicationRole() { Name = StandardRoles.HumanResource, ClientId = null, IsActive = true, CreatedWhen = DateTime.UtcNow, ShortName = StandardRoles.HumanResource.ToLower(), RoleGuid = Guid.NewGuid(), Description = "HumanResource" };

    await _roleManager.CreateAsync(hrRole);
}

它可能对你有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.