4

When I run my application in debug mode my seed method fails because of a 'missing' service. The error message is:

No service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]' has been registered.

Can someone please help me register this service correctly in the StartUp.cs class? Thanks!

RolesConfig.cs

public static class RolesConfig
{

    public static async Task InitialiseAsync(ApplicationDbContext context, IServiceProvider serviceProvider)
    {
        var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        string[] roleNames = {"Admin", "Report", "Search"};
        foreach (var roleName in roleNames)
        {
            var roleExist = await roleManager.RoleExistsAsync(roleName);
            if (!roleExist)
                await roleManager.CreateAsync(new IdentityRole(roleName));
        }
    }
}

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>();
        services.AddHttpClient();
        services.AddHttpClient<IExceptionServiceClient, ExceptionServiceClient>();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
steve
  • 797
  • 1
  • 9
  • 27
  • Where's your `ConfigureServices` method? Presuming you're using ASP.NET Core Identity, are you calling `services.AddDefaultIdentity()` anywhere? – Chris Pickford Feb 25 '19 at 14:20
  • Check this: [ASP.NET Core Identity: No service for role manager](https://stackoverflow.com/questions/41425850/asp-net-core-identity-no-service-for-role-manager) – Fabjan Feb 25 '19 at 14:21
  • 1
    This question is unanswerable without seeing how you've configured your services. In general, if you're getting a service-related exception, that is the first place to look. – Chris Pratt Feb 25 '19 at 14:24
  • @ChrisPratt I have added Startup.cs now – steve Feb 25 '19 at 14:41

4 Answers4

5

I think you're missing the call the AddRoleManager. Here is a similar setup I had, try:

        services.AddIdentity<IdentityUser, IdentityRole>(o => {
            o.Password.RequiredLength = 8;
        })
        .AddRoles<IdentityRole>()
        .AddRoleManager<RoleManager<IdentityRole>>()
        .AddDefaultTokenProviders()
        .AddEntityFrameworkStores<ApplicationDbContext>();
Canica
  • 2,650
  • 3
  • 18
  • 34
4

You most likely need to add

services.AddIdentity<IdentityUser, IdentityRole>(config =>
{
        config.Password.RequireNonAlphanumeric = false; //optional
        config.SignIn.RequireConfirmedEmail = true; //optional
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

in your ConfigureServices method in Startup.cs

  • 1
    this works! many thanks. For anyone else using this answer don't forget to remove `services.AddDefaultIdentity<>` – steve Feb 25 '19 at 15:05
2

In your ConfigureServices method, you're already calling AddDefaultIdentity which is a new addition in 2.1 that scaffolds Identity without role support. To add role support and therefore the RoleManager to your services collection modify your code as below:

services.AddDefaultIdentity<IdentityUser>()
  .AddRoles<IdentityRole>()
  .AddEntityFrameworkStores<ApplicationDbContext>();
  
SmartE
  • 523
  • 5
  • 11
Chris Pickford
  • 8,642
  • 5
  • 42
  • 73
  • 1
    With this method, this error was thrown `InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IRoleStore1[Microsoft.AspNetCore.Identity.IdentityRole]' while attempting to activate 'Microsoft.AspNetCore.Identity.RoleManager1[Microsoft.AspNetCore.Identity.IdentityRole]'.` – steve Feb 25 '19 at 15:12
  • The order in which the services are added matters too (in some cases). ``AddEntityFrameworkStores`` should be after ``AddRoles`` – SmartE Mar 05 '21 at 22:06
1

You have to change the default identity

services.AddIdentity<IdentityUser, IdentityRole>()