尝试激活’AuthController’时无法解析类型’Microsoft.AspNetCore.Identity.UserManager`的服务

我在登录控制器中收到此错误。

InvalidOperationException:尝试激活’Automobile.Server.Controllers.AuthController’时,无法解析类型’Microsoft.AspNetCore.Identity.UserManager`1 [Automobile.Models.Account]’的服务。

这是Auth Controller构造函数:

private SignInManager _signManager; private UserManager _userManager; public AuthController(UserManager userManager, SignInManager signManager) { this._userManager = userManager; this._signManager = signManager; } 

这是在startup.cs中的ConfigureServices:

 public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.Configure(Configuration.GetSection("AppSettings")); //var provider = HttpContext.ApplicationServices; //var someService = provider.GetService(typeof(ISomeService)); services.AddDbContext(options => options .UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("Automobile.Server") )); services.AddIdentity(options => { options.User.RequireUniqueEmail = false; }) .AddEntityFrameworkStores() .AddDefaultTokenProviders(); //services.AddScoped<SignInManager, SignInManager>(); //services.AddScoped<UserManager, UserManager>(); services.AddMvc(); App.Service = services.BuildServiceProvider(); // Adds a default in-memory implementation of IDistributedCache. services.AddDistributedMemoryCache(); services.AddSession(options => { // Set a short timeout for easy testing. options.IdleTimeout = TimeSpan.FromSeconds(10); options.CookieHttpOnly = true; }); } 

您需要在SignInManager,UserManager和services.AddIdentity中使用相同的用户数据模型。 如果您使用自己的自定义应用程序角色模型类,则相同的主体是正确的。

所以,改变

 services.AddIdentity(options => { options.User.RequireUniqueEmail = false; }) .AddEntityFrameworkStores() .AddDefaultTokenProviders(); 

 services.AddIdentity(options => { options.User.RequireUniqueEmail = false; }) .AddEntityFrameworkStores() .AddDefaultTokenProviders(); 

只是为了清楚答案:

如果在startup.cs中使用ApplicationUser类: services.AddIdentity()

那么在注入时你必须在你的控制器中使用相同的类:

 public AccountController(UserManager userManager) 

如果您使用其他类,例如:

 public AccountController(UserManager userManager) 

那么你会得到这个错误:

InvalidOperationException:无法解析类型’Microsoft.AspNetCore.Identity.UserManager`1 [IdentityUser]’的服务

因为您在启动时使用了ApplicationUser ,而不是IdentityUser因此此类型未在注入系统中注册。