title: Blazor - Identity Add roles on application startup
body: <p>I started an application in Blazor .net 3.1, and I'm having a problem. I will want to add a user with an admin role (root) when starting the application. I am using EF. Adding the user works, but adding roles throws me an exception.</p>
  <p><a href="https://i.stack.imgur.com/Ynvew.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ynvew.jpg" alt="Image exception" /></a></p>
  <pre><code>System.AggregateException : 'No service for type 'Microsoft.AspNetCore.Identity.RoleManager'1[Microsoft.AspNEtCore.Identity.IdentityRole]' has been registered.ontainer is destroyed)'
  </code></pre>
  <p>I have tried different solutions, like <a href="https://stackoverflow.com/questions/39934201/asp-net-core-identity-add-custom-user-roles-on-application-startup">ASP.NET Core Identity Add custom user roles on application startup</a>, <a href="https://techbrij.com/asp-net-core-identity-seed-roles-users" rel="nofollow noreferrer">old post</a> but I still have the same exception, on SQLite, SQL Server,...</p>
  <p>I created a static class and in the Startup.cs I call this method.</p>
  <pre><code>public static class RolesData
  {
      private static readonly string[] Roles = new string[] { &quot;Admin&quot;, &quot;Manager&quot;, &quot;Member&quot; };
  
      public static async Task SeedRoles(IServiceProvider serviceProvider)
      {
          using (var serviceScope = serviceProvider.GetRequiredService&lt;IServiceScopeFactory&gt;().CreateScope())
          {
              var roleManager = serviceScope.ServiceProvider.GetRequiredService&lt;RoleManager&lt;IdentityRole&gt;&gt;();
              foreach (var role in Roles)
              {
                  if (!await roleManager.RoleExistsAsync(role))
                  {
                      await roleManager.CreateAsync(new IdentityRole(role));
                  }
              }
          }
      }
  }
  
  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
      ...
      RolesData.SeedRoles(app.ApplicationServices).Wait();
  }
  </code></pre>
  <p>If you have any suggestions I'm interested, and also if you know of a site that explains authentication with Identity, I want to understand!</p>
  <p>Thank you for your help</p>