1

In .NET Core 3.1, we were able to create roles on startup like this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
{
  CreateRoles(serviceProvider).Wait;
}
private async Task CreateRoles(IServiceProvider serviceProvider)
        {
            var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        .... //do your thing with the RoleManager instance.

}

However, in .NET 7 (and in 6 as well) the Configure method is not there from where we can get an instance of IServiceProvider.

How do I do that in .NET 7?

user3656651
  • 619
  • 1
  • 9
  • 25

1 Answers1

4

You have to Create a scope then access the RoleManager<> from there.

Program.cs

...

using var scope = app.Services.CreateScope();
using var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();

...
app.Run();

Brian Parker
  • 11,946
  • 2
  • 31
  • 41