DERK
DERK

Reputation: 11

ASP.NET Core 2 seeding roles and users

public class DbInitializer 
{
    public static async Task CreateAdmin(IServiceProvider service)
    {
        UserManager<AppUser> userManager = service.GetRequiredService<UserManager<AppUser>>();
        RoleManager<IdentityRole> roleManager = service.GetRequiredService<RoleManager<IdentityRole>>();

        string username = "Admin";
        string email = "[email protected]";
        string pass = "Secrete90";
        string role = "Admins";

        if(await userManager.FindByNameAsync(username)== null)
        {
            if(await roleManager.FindByNameAsync(role)== null)
            {
                await roleManager.CreateAsync(new IdentityRole(role));
            }
            var user = new AppUser { UserName = username, Email = email };

            var result = await userManager.CreateAsync(user, pass);
            if (result.Succeeded) { await userManager.AddToRoleAsync(user, role); }
        }
    }

When I run this code on start up, I get an error about not being able to scope the code in the startup class.

DbInitializer.CreateAdmin(app.ApplicationServices).Wait();

Upvotes: 1

Views: 718

Answers (1)

Paul
Paul

Reputation: 12440

In .NET Core 2 calling your seed logic needs to be moved to the Main method of the program.cs class.

Example Program.cs

public static void Main(string[] args) {
    var host = BuildWebHost(args);
    using (var scope = host.Services.CreateScope()) {
        var services = scope.ServiceProvider;
        var userManager = services.GetRequiredService<UserManager<AppUser>>();
        var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
        DbInitializer.CreateAdmin(userManager, roleManager).Wait();
    }
    host.Run();
}

Updated DbInitializer

public class DbInitializer 
{
    public static async Task CreateAdmin(UserManager<AppUser> userManager, RoleManager<IdentityRole> roleManager)
    {

        string username = "Admin";
        string email = "[email protected]";
        string pass = "Secrete90";
        string role = "Admins";

        if(await userManager.FindByNameAsync(username)== null)
        {
            if(await roleManager.FindByNameAsync(role)== null)
            {
                await roleManager.CreateAsync(new IdentityRole(role));
            }
            var user = new AppUser { UserName = username, Email = email };

            var result = await userManager.CreateAsync(user, pass);
            if (result.Succeeded) { await userManager.AddToRoleAsync(user, role); }
        }
    }

Upvotes: 1

Related Questions