This is part of my code:
public void ConfigureServices(IServiceCollection services)
{
options.Events = new CookieAuthenticationEvents() {
OnValidatePrincipal = async (c) =>
{
//using (ServiceProvider serviceProvider = builder.Services.BuildServiceProvider()) // ASP0000
//{
// var userManager = serviceProvider.GetRequiredService<UserManager<MyUser>>();
//var myUser = await userManager.GetUserAsync(c.Principal);
//if (myUser != null && !myUser.EmailConfirmed)
//{
// c.RejectPrincipal();
//}
//}
}
};
});
}
When uncommented it works, but there is a warning (green underline) on BuildServiceProvider method saying that:
ASP0000: Calling BuildServiceProvider from application code results in an additional copy of singleton services being created.
So what is the alternative to get UserManager in ConfigureServices? I cannot inject it as ConfigureServices method accepts only zero or one parameter, which must be IServiceCollection.
CodePudding user response:
You should not build provider and resolve something from it inside the handler (it is definitely not an operation you want to do for each principal validation), just use the context parameter of it:
new CookieAuthenticationEvents
{
OnValidatePrincipal = context =>
{
var userManager = context.HttpContext.RequestServices.GetRequiredService<UserManager<MyUser>>();
}
}
