Instance of RoleManager/IServiceProvider in .NET 7 Blazor

443 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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();