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

时间:2017-06-11 11:57:49

标签: 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;
    }

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

    }

7 个答案:

答案 0 :(得分:47)

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

所以,改变

browser.PrintToPdfAsync(@"C:\out.pdf", new PdfPrintSettings
{
    BackgroundsEnabled = true,
    HeaderFooterEnabled = false,
    Landscape = false,

    MarginType = CefPdfPrintMarginType.Custom,
    MarginBottom = 0,
    MarginTop = 0,
    MarginLeft = 0,
    MarginRight = 0,

    PageWidth =  210000,
    PageHeight = 297000
});

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

答案 1 :(得分:27)

要明确答案:

如果您在startup.cs中使用课程ApplicationUserservices.AddIdentity<ApplicationUser, IdentityRole>()

然后在注入时必须在控制器中使用相同的类:

public AccountController(UserManager<ApplicationUser> userManager)

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

public AccountController(UserManager<IdentityUser> userManager)

然后你会收到这个错误:

  

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

的服务

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

答案 2 :(得分:3)

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

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

OR

您可以直接在AddIdentity中进行配置:

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

答案 3 :(得分:1)

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

services.AddIdentityCore<YourAppUser>()

然后,您将需要手动注册AddIdentity所做的工作,可以在这里找到: enter image description here

        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

答案 4 :(得分:1)

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

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

答案 5 :(得分:0)

如果您使用的是“ IdentityServer”,则IdentityServer会对用户进行身份验证并授权客户端。默认情况下,IdentityServer实际上与用户管理无关。但是对asp.net Identity

有一些支持

因此您需要添加:

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

答案 6 :(得分:0)

您需要使用以下内容更新Statup.cs类

services.AddIdentity () .AddEntityFrameworkStores();

这里:ApplicationUser是我的自定义模型类。