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

OMI*_*MID 63 c# asp.net asp.net-mvc asp.net-core asp.net-core-identity

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

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

这是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;
    }
Run Code Online (Sandbox Code Playgroud)

这是在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;
        });

    }
Run Code Online (Sandbox Code Playgroud)

Hoj*_*atK 60

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

所以,改变

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

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

  • 我有类似的问题,我有我的客户用户和角色在AddIdentity方法中定义,我仍然得到相同的错误.知道为什么吗?我可以在一个单独的线程中发布我的代码. (2认同)

Gre*_*Gum 33

只是为了清楚答案:

如果您ApplicationUser在startup.cs中使用该类:services.AddIdentity<ApplicationUser, IdentityRole>()

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

public AccountController(UserManager<ApplicationUser> userManager)
Run Code Online (Sandbox Code Playgroud)

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

public AccountController(UserManager<IdentityUser> userManager)
Run Code Online (Sandbox Code Playgroud)

那么你会得到这个错误:

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

因为你ApplicationUser在启动时使用过,IdentityUser所以这种类型没有在注射系统中注册.

  • 这将计入所有引用,因此如果您为asp.net core 2.1实现新的Razor标识以替换旧的标识系统,则需要将其自动实现的内容(如SignInManager <IdentityUser>)替换为SignInManager <ApplicationUser>,无论它在何处使用.这可能很烦人.此外,您需要从正常/帐户/登录到/身份/帐户/登录等重新路由只是一些提示,以帮助;) (5认同)

Mah*_*yar 11

您可以在Startup类中的ConfigureServices中分别设置IdentityUser和IdentityRole,如下所示:

services.AddDefaultIdentity<IdentityUser>()
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)

或者

您可以直接配置到 AddIdentity:

services.AddIdentity<IdentityUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)

  • 如果仅使用代码答案,OP 和其他人将很难了解该问题,请考虑编辑您的答案并添加解释 (7认同)

Ser*_*gan 8

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

services.AddIdentityCore<YourAppUser>()
Run Code Online (Sandbox Code Playgroud)

然后,您将需要手动注册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>>();
Run Code Online (Sandbox Code Playgroud)

您需要替换TUser并替换TRole为这些实现,或者使用默认的实现IdentityUserIdentityRole

  • 这正是我所缺少的。将 `TryAddScoped&lt;UserManager&lt;TUser&gt;&gt;();` 和 `services.TryAddScoped&lt;SignInManager&lt;TUser&gt;&gt;();` 添加到我的 Startup.cs 解决了我的问题。 (3认同)

Ozz*_*zzy 6

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

services.AddDefaultIdentity<IdentityUser>()
    .AddRoles<IdentityRole>() // <--------
    .AddDefaultUI(UIFramework.Bootstrap4)
    .AddEntityFrameworkStores<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)