无法获取UserManager类

本文关键字:UserManager 获取 | 更新日期: 2023-09-27 18:13:01

我要做的是添加一个新的admin用户并将其分配给admin角色。所以. .我去Configure方法中的Startup.cs类,并编写了以下代码:

var context = app.ApplicationServices.GetService<ApplicationDbContext>();
// Getting required parameters in order to get the user manager
var userStore = new UserStore<ApplicationUser>(context);
// Finally! get the user manager!
var userManager = new UserManager<ApplicationUser>(userStore);

但是,我得到以下错误消息:

项目文件行抑制状态参数没有给出对应的参数所需的形式参数"optionsAccessor"UserManager。UserManager (IUserStoreIOptions IPasswordHasher,IEnumerable>,ILookupNormalizer IEnumerable>,IdentityErrorDescriber IServiceProvider,"FinalProject. NETCoreApp,Version=v1.0 C:'Users'Or"•' ' Visual Studio的文档2015'Projects'FinalProject'src'FinalProject'Startup.cs 101 Active

这个错误要了我的命。显然,我需要userManager来创建新用户但我无法初始化这个

无法获取UserManager类

您可以使用依赖注入来获取UserManager的实例。只需在configure方法中添加一个参数,如下所示:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)

可以创建用户和角色。我通常把这段代码移到一个静态类中…

public static class DbInitializer
{
    public static async Task Initialize(ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
    {
        // Ensure that the database exists and all pending migrations are applied.
        context.Database.Migrate();
        // Create roles
        string[] roles = new string[] { "UserManager", "StaffManager" };
        foreach (string role in roles)
        {
            if (!await roleManager.RoleExistsAsync(role))
            {
                await roleManager.CreateAsync(new IdentityRole(role));
            }
        }
        // Create admin user
        if (!context.Users.Any())
        {
            await userManager.CreateAsync(new ApplicationUser() { UserName = "info@example.com", Email = "info@example.com" }, "p@ssw0rd");
        }
        // Ensure admin privileges
        ApplicationUser admin = await userManager.FindByEmailAsync("info@example.com");
        foreach (string role in roles)
        {
            await userManager.AddToRoleAsync(admin, role);
        }
    }
}

…并在Startup中调用该方法。配置方法:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
    // Code omitted for brevity
    // Create seed data
    DbInitializer.Initialize(context, userManager, roleManager).Wait();
}

在Entity Framework Core的下一个版本中,数据库播种将作为一个特性被添加。

正如@JuliusHardt所说,你可以通过依赖注入获得UserManager的实例。对于播种数据库,首先创建如下的扩展方法:

public static class ApplicationDbContextExtensions
{
    public static void EnsureSeedData(this ApplicationDbContext context, UserManager<ApplicationUser> userManager)
    {
        if (!context.Users.Any())
        {
            var result = userManager.CreateAsync(
                new ApplicationUser { UserName = "info@example.com", Email = "info@example.com" },
                "P@ssw0rd").Result;
        }
    }
}

Startup类和Configure法:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseDatabaseErrorPage();
    app.UseBrowserLink();
    using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
    {
        // First apply pendding migrations if exist
        serviceScope.ServiceProvider.GetService<ApplicationDbContext>().Database.Migrate();
        // Then call seeder method
        var userManager = serviceScope.ServiceProvider.GetService<UserManager<ApplicationUser>>();
        serviceScope.ServiceProvider.GetService<ApplicationDbContext>().EnsureSeedData(userManager);
    }
}