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.IRoleStore
1[Microsoft.AspNetCore.Identity.IdentityRole]' while attempting to activate 'Microsoft.AspNetCore.Identity.AspNetRoleManager
1[Microsoft.AspNetCore.Identity.IdentityRole]'.
services.AddDbContext<AppDbContext>(option =>
option.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<AppUser, IdentityRole>(options => { });
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?
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>();
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With