Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IRoleStore

I'm trying to seed UserRole in my ASP.NET Core MVC App, but it's throwing the following exception.

Exception thrown: 'System.InvalidOperationException' in Microsoft.Extensions.DependencyInjection.dll An exception of type 'System.InvalidOperationException' occurred in Microsoft.Extensions.DependencyInjection.dll but was not handled in user code Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IRoleStore1[Microsoft.AspNetCore.Identity.IdentityRole]' while attempting to activate 'Microsoft.AspNetCore.Identity.AspNetRoleManager1[Microsoft.AspNetCore.Identity.IdentityRole]'.

Add service

services.AddDbContext<AppDbContext>(option =>
               option.UseSqlServer(
               Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<AppUser, IdentityRole>(options => { }); 

Seed

private void CreateRoles(IServiceProvider serviceProvider)
{
    var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var userManager = serviceProvider.GetRequiredService<UserManager<SchoolUser>>();
        .................
        .................
}

I'm calling the CreateRoles()inside the Configure() of Startup.cs and it throwing the above exception at first line of the CreateRoles(). Exception saying that it's DependencyInjection problem, how can I solve this issue?

like image 327
Sabir Hossain Avatar asked Jan 02 '23 14:01

Sabir Hossain


2 Answers

It looks like you're intending to use Entity Framework Core for your ASP.NET Core Identity persistence, but you haven't quite set this up yet. IRoleStore et al are not registered by default, as this is an extension point to allow for different persistence mechanisms to be used. In order to use EF core here, you just need to add a call to AddEntityFrameworkStores, like so:

services.AddIdentity<AppUser, IdentityRole>()
    .AddEntityFrameworkStores<AppDbContext>();
like image 131
Kirk Larkin Avatar answered Jan 09 '23 00:01

Kirk Larkin


According the MSDN document, most effective way is

    services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>() <--Here!!!
     .AddEntityFrameworkStores<ApplicationDbContext>();
like image 39
Simplerjiang Avatar answered Jan 08 '23 23:01

Simplerjiang