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?
CodePudding user response:
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();