DanielC
DanielC

Reputation: 472

ASP.NET 5 (MVC6) How to seed users

How would you seed users? I am following their documents here, but they only show how to seed data that is inserted directly by the ApplicationDbContext.

In the Account controller, the UserManager is created through DI. How would I instantiate a UserManager in the Seed method?

 public class SeedData
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        var context = serviceProvider.GetService<ApplicationDbContext>();
        var userManager = serviceProvider.GetService<UserManager<ApplicationUser>>();

Then in Startup.cs in the Configure method:

SeedData.Initialize(app.ApplicationServices);

Upvotes: 4

Views: 2454

Answers (2)

Muqeet Khan
Muqeet Khan

Reputation: 2124

You would create a class in the lines of

    public class UserSeed
    {
        private ApplicationDbContext _context;
        private UserManager<ApplicationUser> _mgr;

        public UserSeed(ApplicationDbContext context,UserManager<ApplicationUser> userManager)
        {
            _context = context;
            _mgr = users;
        }

        public void UserSeedData()
        {

            var user = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" };

            var result = _mgr.CreateAsync(user,"fooPassword");
......
......

       }
}

In the configure method of your startup.cs take userSeed through DI like

public async void Configure(...., UserSeed userSeedData)

and then inside the method you call

userSeedData.UserSeedData();

Don't use this code as is, you would probably want to check if the user already exists before you create it.

Note: This method will run once every time your application starts.

Upvotes: 0

SynerCoder
SynerCoder

Reputation: 12776

In the startup.cs in the configure method, you can add the following code to get the UserManager and from there seed the users.

var userManager = app.ApplicationServices.GetService<UserManager<ApplicationUser>>();

Upvotes: 5

Related Questions