[英]How to inject UserManager to Program.cs or Startup.cs
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:取消注释时,它可以工作,但是 BuildServiceProvider 方法上有一个警告(绿色下划线)说:
ASP0000: Calling BuildServiceProvider from application code results in an additional copy of singleton services being created.
ASP0000:从应用程序代码调用 BuildServiceProvider 会导致创建 singleton 服务的额外副本。
So what is the alternative to get UserManager in ConfigureServices?那么在 ConfigureServices 中获取 UserManager 的替代方法是什么? I cannot inject it as ConfigureServices method accepts only zero or one parameter, which must be IServiceCollection.
我不能注入它,因为 ConfigureServices 方法只接受零个或一个参数,它必须是 IServiceCollection。
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>>();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.