Подтвердить что ты не робот

Не удалось разрешить службу для типа "Microsoft.AspNetCore.Identity.UserManager" при попытке активировать "AuthController"

Я получаю эту ошибку в контроллере входа.

InvalidOperationException: не удается разрешить службу для типа "Microsoft.AspNetCore.Identity.UserManager`1 [Automobile.Models.Account]" при попытке активировать "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;
    }

а здесь ConfigureServices в startup.cs:

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

    }
4b9b3361

Ответ 1

Вам нужно использовать одну и ту же модель пользовательских данных в SignInManager, UserManager и services.AddIdentity. Тот же самый принцип является истинным, если вы используете свой собственный класс ролевых моделей приложений.

Итак, измените

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();

Ответ 2

Просто чтобы прояснить ответ:

Если вы используете класс ApplicationUser в файле startup.cs: services.AddIdentity<ApplicationUser, IdentityRole>()

тогда вы должны использовать тот же класс в вашем контроллере, когда вводите его:

public AccountController(UserManager<ApplicationUser> userManager)

Если вы используете какой-то другой класс, такой как:

public AccountController(UserManager<IdentityUser> userManager)

тогда вы получите эту ошибку:

InvalidOperationException: невозможно разрешить службу для типа "Microsoft.AspNetCore.Identity.UserManager'1 [IdentityUser]"

потому что вы использовали ApplicationUser при запуске, а не IdentityUser поэтому этот тип не зарегистрирован в системе впрыска.

Ответ 3

Это немного не связано с оригинальным постом, но так как Google приводит вас сюда... если вы получаете эту ошибку и используете:

services.AddIdentityCore<YourAppUser>()

Затем вам нужно будет вручную зарегистрировать материал, который делает AddIdentity, который можно найти здесь: https://github.com/aspnet/Identity/blob/feedcb5c53444f716ef5121d3add56e11c7b71e5/src/Identity/IdentityServiceCollectionExtensions.cs#79

        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>>();

Вам нужно будет заменить TUser и TRole своими реализациями тех или IdentityUser по умолчанию, IdentityRole

Ответ 4

не забудьте добавить менеджер ролей в ConfigureServices

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