Home > OS >  How to access UserManager<IdentityUser> instance from WebApplication instance app in program.c
How to access UserManager<IdentityUser> instance from WebApplication instance app in program.c

Time:01-28

I need to access UserManager instance to seed IdentityUser data, I am doing in program.cs file Below is given code snippet

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services
    .AddDefaultIdentity<MyIdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<AppDbContext>();

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
});

builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();


builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.MapControllers();

app.MapControllerRoute(
        name: "default",
        pattern: "{controller = Home}/{action = Index}/{Id?}"
    );
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapDefaultControllerRoute();
app.MapRazorPages();

var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
var scope = scopeFactory.CreateScope();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<MyIdentityUser>>();

SeedInitialData.SeedData(roleManager, userManager);

app.Run();

and I receive this exception

InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered. Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)

Please help me, how to find this issue. regards

I read many articles, and I tried some of them, none of them worked for me.

CodePudding user response:

I create a simple demo to show how to seed data to identity in asp.net core, You can refer to it.

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        //.........

        builder.Services.AddIdentity<IdentityUser,IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();
        

        var app = builder.Build();

        // Configure the HTTP request pipeline.
        //........
        app.UseAuthorization();

        using (var scope = app.Services.CreateScope())
        {
            //Resolve ASP .NET Core Identity with DI help
            var userManager = (UserManager<IdentityUser>)scope.ServiceProvider.GetService(typeof(UserManager<IdentityUser>));
            var roleManager = (RoleManager<IdentityRole>)scope.ServiceProvider.GetService(typeof(RoleManager<IdentityRole>));
            // do you things here

            MyIdentityDataInitializer.SeedData(userManager, roleManager);
        }

       //........

        app.Run();
    }
}

MyIdentityDataInitializer class

public static  class MyIdentityDataInitializer
    {
        public static void SeedData(UserManager<IdentityUser> userManager,RoleManager<IdentityRole> roleManager)
        {
            SeedRoles(roleManager);
            SeedUsers(userManager);
        }

        public static void SeedUsers(UserManager<IdentityUser> userManager)
        {
            if (userManager.FindByNameAsync("user1").Result == null)
            {
                IdentityUser user = new IdentityUser();
                user.UserName = "user1";
                user.Email = "user1@localhost";               
                IdentityResult result = userManager.CreateAsync(user, "Password123!!!").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user,
                                        "NormalUser").Wait();
                }
            }


            if (userManager.FindByNameAsync("user2").Result == null)
            {
                IdentityUser user = new IdentityUser();
                user.UserName = "user2";
                user.Email = "user2@localhost";
                IdentityResult result = userManager.CreateAsync(user, "Password123!!!").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user,
                                        "Administrator").Wait();
                }
            }
        }

        public static void SeedRoles(RoleManager<IdentityRole> roleManager)
        {
            if (!roleManager.RoleExistsAsync("NormalUser").Result)
            {
                IdentityRole role = new IdentityRole();
                role.Name = "NormalUser";
                
                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }


            if (!roleManager.RoleExistsAsync("Administrator").Result)
            {
                IdentityRole role = new IdentityRole();
                role.Name = "Administrator";
               
                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }
        }
    }

Now when I run my project, The data will be seeded successfully.

enter image description here

enter image description here

  • Related