I am trying to seed my database and add roles to my ASP.NET Core Web Application. In the tutorial I am following, it advised to add the following to the Configure() method:
app.UseAuthentication();
MyIdentityDataInitializer.SeedData(userManager, roleManager);
I had no issues with the first line, but with the second, I am getting an error saying userManager and roleManager doesn't exist which makes sense because if i were using .NET 5 my configure method would've looked like this and been fine:
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
UserManager<MyIdentityUser> userManager,
RoleManager<MyIdentityRole> roleManager)
{
...
app.UseAuthentication();
MyIdentityDataInitializer.SeedData(userManager, roleManager);
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
But in .NET 6 I'm not sure how to.
Can someone advise on this please?
CodePudding user response:
In .NET 6, Microsoft has removed the Startup.cs
class where your Configure()
method was previously defined. Instead, configuration of both the DI service container (which was done previously in the ConfigureServices(IServiceCollection)
) method) and the AspNet Core Application Builder are done directly in Program.cs
Now since there is nothing automatically calling the Configure()
method for you (and injecting those values for you), you'll have to get references to those objects yourself using the ServiceProvider. Your Program.cs
will probably look something like this:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// add services that were previously added in ConfigureServices()
var app = builder.Build();
var userManager = app.Services.GetRequiredService<UserManager<MyIdentityUser>>();
var roleManager = app.Services.GetRequiredService<RoleManager<MyIdentityRole>>();
MyIdentityDataInitializer.SeedData(userManager, roleManager);
app.UseAuthentication();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});