无法获取UserManager类

时间:2016-10-13 17:28:32

标签: c# asp.net-core asp.net-core-mvc user-roles

我要做的是添加一个新的管理员用户并为其分配管理员角色。 所以..我在Startup.cs方法中转到了Configure类,并编写了以下代码:

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);

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

  

严重级代码描述项目文件行抑制状态   错误CS7036没有给出对应的参数   需要形式参数'optionsAccessor'   UserManager.UserManager(IUserStore,   IOptions,IPasswordHasher,   IEnumerable的&gt;中   IEnumerable&gt;,ILookupNormalizer,   IdentityErrorDescriber,IServiceProvider,   ILogger&gt;)'FinalProject..NETCoreApp,Version = v1.0 C:\ Users \ Or   Natan \ Documents \ Visual Studio   2015 \ Projects \ FinalProject \ src \ FinalProject \ Startup.cs 101活动

这个错误在这里杀了我..显然我需要userManager才能创建新用户但是我无法初始化这个东西。

2 个答案:

答案 0 :(得分:4)

您可以使用dependency injection获取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.Configure方法中调用该方法:

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 database seeding will be added as a feature的下一个版本中。

答案 1 :(得分:0)

正如@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);
    }
}