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

Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager` while attempting to activate 'AuthController'

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

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Automobile.Models.Account]' while attempting to activate 'Automobile.Server.Controllers.AuthController'.

这是 Auth Controller 构造函数:

private SignInManager<Automobile.Models.Account> _signManager;
    private UserManager<Automobile.Models.Account> _userManager;

    public AuthController(UserManager<Models.Account> userManager,
                          SignInManager<Automobile.Models.Account> signManager)
    {
        this._userManager = userManager;
        this._signManager = signManager;
    }

这里是 startup.cs 中的 ConfigureServices:

public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);
        services.Configure<AppConfig>(Configuration.GetSection("AppSettings"));

        //var provider = HttpContext.ApplicationServices;
        //var someService = provider.GetService(typeof(ISomeService));


        services.AddDbContext<Providers.Database.EFProvider.DataContext>(options => options
            .UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                 b => b.MigrationsAssembly("Automobile.Server")
            ));


        services.AddIdentity<IdentityUser, IdentityRole>(options =>
        {
            options.User.RequireUniqueEmail = false;
        })
        .AddEntityFrameworkStores<Providers.Database.EFProvider.DataContext>()
        .AddDefaultTokenProviders(); 
        //services.AddScoped<SignInManager<Automobile.Models.Account>, SignInManager<Automobile.Models.Account>>();
        //services.AddScoped<UserManager<Automobile.Models.Account>, UserManager<Automobile.Models.Account>>();

        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 中使用相同的用户数据模型。如果您使用自己的自定义应用程序角色模型 class.

,则原理相同

所以,改变

services.AddIdentity<IdentityUser, IdentityRole>(options =>
    {
        options.User.RequireUniqueEmail = false;
    })
    .AddEntityFrameworkStores<Providers.Database.EFProvider.DataContext>()
    .AddDefaultTokenProviders();

services.AddIdentity<Automobile.Models.Account, IdentityRole>(options =>
    {
        options.User.RequireUniqueEmail = false;
    })
    .AddEntityFrameworkStores<Providers.Database.EFProvider.DataContext>()
    .AddDefaultTokenProviders();

只是为了明确答案:

如果在startup.cs中使用classApplicationUserservices.AddIdentity<ApplicationUser, IdentityRole>()

然后你必须在你的控制器中使用相同的 class 注入它:

public AccountController(UserManager<ApplicationUser> userManager)

如果您使用其他 class 例如:

public AccountController(UserManager<IdentityUser> userManager)

然后你会得到这个错误:

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[IdentityUser]'

因为你在启动时使用了ApplicationUser,而不是IdentityUser所以这个类型没有在注入系统中注册。

这与原来的 post 有点无关,但是由于 Google 将您带到这里...如果您遇到此错误并且正在使用:

services.AddIdentityCore<YourAppUser>()

然后你需要手动注册 AddIdentity 做的事情,可以在这里找到: https://github.com/aspnet/Identity/blob/feedcb5c53444f716ef5121d3add56e11c7b71e5/src/Identity/IdentityServiceCollectionExtensions.cs#L79

        services.AddHttpContextAccessor();
        // Identity services
        services.TryAddScoped<IUserValidator<TUser>, UserValidator<TUser>>();
        services.TryAddScoped<IPasswordValidator<TUser>, PasswordValidator<TUser>>();
        services.TryAddScoped<IPasswordHasher<TUser>, PasswordHasher<TUser>>();
        services.TryAddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>();
        services.TryAddScoped<IRoleValidator<TRole>, RoleValidator<TRole>>();
        // No interface for the error describer so we can add errors without rev'ing the interface
        services.TryAddScoped<IdentityErrorDescriber>();
        services.TryAddScoped<ISecurityStampValidator, SecurityStampValidator<TUser>>();
        services.TryAddScoped<ITwoFactorSecurityStampValidator, TwoFactorSecurityStampValidator<TUser>>();
        services.TryAddScoped<IUserClaimsPrincipalFactory<TUser>, UserClaimsPrincipalFactory<TUser, TRole>>();
        services.TryAddScoped<UserManager<TUser>>();
        services.TryAddScoped<SignInManager<TUser>>();
        services.TryAddScoped<RoleManager<TRole>>();

您需要将 TUserTRole 替换为您的实现,或者默认的 IdentityUserIdentityRole

不要忘记在 ConfigureServices 中添加角色管理器

services.AddDefaultIdentity<IdentityUser>()
    .AddRoles<IdentityRole>() // <--------
    .AddDefaultUI(UIFramework.Bootstrap4)
    .AddEntityFrameworkStores<ApplicationDbContext>();

如果您正在使用 "IdentityServer" 以便 IdentityServer 对用户进行身份验证并授权 client.By 默认值,IdentityServer 实际上与用户管理无关。但是有一些支持 asp.net Identity

所以你需要添加:

services.AddIdentityServer()
    .AddAspNetIdentity<ApplicationUser>();

您可以在 Startup class 中的 ConfigureServices 中单独设置 IdentityUser 和 IdentityRole,如下所示:

services.AddDefaultIdentity<IdentityUser>()
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

你可以直接配置到AddIdentity:

services.AddIdentity<IdentityUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

您需要更新您的 Statup.cs class

services.AddIdentity() .AddEntityFrameworkStores();

此处:ApplicationUser 是我的自定义模型 class。