Search code examples
c#asp.net-coreasp.net-identityasp.net-core-6.0

How to call SeedRoles method in Program.cs


I'm trying to build an authorization system (role-based authorization) for my app.

I have seed roles class but I don't know the right way to call the seed method in Program.cs to run every time when the app runs like this code :

using login_and_registration.Areas.Identity.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;

namespace login_and_registration.Models
{
    public class SeedRoles
    {

        public static void Initialize(IServiceProvider serviceProvider)
        {
            var context = serviceProvider.GetService<lAppregistrationContext>();

            string[] roles = new string[] { "Owner", "Administrator", "Tests2", "Editor", "Buyer", "Business", "Seller", "Subscriber" };

            foreach (string role in roles)
            {
                var roleStore = new RoleStore<IdentityRole>(context);

                if (!context.Roles.Any(r => r.Name == role))
                {
                    roleStore.CreateAsync(new IdentityRole(role));
                }
            }

            context.SaveChangesAsync();
        }
    }
}

Solution

  • The SeedRoles class should be a static class, you can modify it as below:

    //required
    //using Microsoft.AspNetCore.Identity;
    //using Microsoft.EntityFrameworkCore;
    public static class SeedRoles
    {
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new ApplicationDbContext(serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
            {
                string[] roles = new string[] { "Owner", "Administrator", "Tests2", "Editor", "Buyer", "Business", "Seller", "Subscriber" };
    
                var newrolelist = new List<IdentityRole>();
                foreach (string role in roles)
                {  
                    if (!context.Roles.Any(r => r.Name == role))
                    {
                        newrolelist.Add(new IdentityRole(role));
                    }
                }
                context.Roles.AddRange(newrolelist);
                context.SaveChanges();
            }
        }
    }
    

    Note: In my application, the DB context is ApplicationDbContext, you can chnage it to yours.

    Then, in the program.cs file, you can call the seed role method after the var app = builder.Build(); line, code like this:

    // Add services to the container.
    var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
    builder.Services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(connectionString));
    builder.Services.AddDatabaseDeveloperPageExceptionFilter();
    
    builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddRoles<IdentityRole>()    //enable Identity Role
        .AddEntityFrameworkStores<ApplicationDbContext>() ;
    builder.Services.AddControllersWithViews();
    
    var app = builder.Build();
    
    using (var scope = app.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
    
        SeedRoles.Initialize(services);
    }
    

    The result as below:

    enter image description here

    More detail information, you can check the official document and sample.