Pavol
Pavol

Reputation: 582

Accessing UserManager with PasswordHasher outside of controller

I have web app using asp.net core 2.0 with identity and entity framework core. I am trying to create few users after DB is created. I created DbInitializer class which is called from Program.Main()

    public static void Main(string[] args)
    {
        var host = BuildWebHost(args);

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            try
            {
                var context = services.GetRequiredService<ApplicationDbContext>();
                DbInitializer.Initialize(context);
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occurred while seeding the database.");
            }
        }

        host.Run();
    }

Problem is that I cannot access UserManager whit right PasswordHasher in my class. I try this answer, and I created new UserManager like this

 var store = new UserStore<ApplicationUser>(context);
 var hasher = new PasswordHasher<ApplicationUser>();
 var manager = new UserManager<ApplicationUser>(store, null, hasher, null, null, null, null, null, null);
 await manager.CreateAsync(user, "password");

And then I create user. User is created and I can see him in DB, problem is that I cannot log in with given password. I think the problem is that I created new PasswordHasher. How can I access UserManager that is used in application?..

Upvotes: 0

Views: 723

Answers (1)

Jared Plaisted
Jared Plaisted

Reputation: 11

I ran into a similar problem while trying to seed Users into my database, heres how I solved it.

Try passing services instead of context to your Initialize method:

DbInitializer.Initialize(services);

Then update your Initialize method:

public static void Initialize(IServiceProvider services) {

    var context = services.GetRequiredService<ApplicationDbContext>();
    //Do stuff with context        

    //Obtain reference to UserManager
    var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();

    // Set properties for new User
    ApplicationUser user = new ApplicationUser
    {
        UserName = "[email protected]",
        Email = "[email protected]"
    };

    //Set password
    string password = "Change.Me99";

    //Create new user
    var result = userManager.CreateAsync(user, password);

    //Check the result
}

Upvotes: 1

Related Questions