web-dev-qa-db-ja.com

「AuthController」をアクティブ化しようとしているときに、「Microsoft.AspNetCore.Identity.UserManager」タイプのサービスを解決できません

Login Controllerでこのエラーが発生しています。

InvalidOperationException:「Automobile.Server.Controllers.AuthController」をアクティブにしようとしたときに、「Microsoft.AspNetCore.Identity.UserManager`1 [Automobile.Models.Account]」タイプのサービスを解決できません。

認証コントローラのコンストラクタは次のとおりです。

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

    }
48
OMID

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

答えを明確にするために:

Startup.csでApplicationUserクラスを使用する場合:services.AddIdentity<ApplicationUser, IdentityRole>()

次に、注入するときにコントローラーで同じクラスを使用する必要があります。

public AccountController(UserManager<ApplicationUser> userManager)

次のような他のクラスを使用する場合:

public AccountController(UserManager<IdentityUser> userManager)

このエラーが発生します:

InvalidOperationException:タイプ 'Microsoft.AspNetCore.Identity.UserManager`1 [IdentityUser]'のサービスを解決できません

起動時にApplicationUserではなくIdentityUserを使用したため、このタイプはインジェクションシステムに登録されません。

30
Greg Gum

これは元の投稿とは少し関係がありませんが、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に置き換える必要があります。

4
Serj Sagan

configureServicesにロールマネージャーを追加することを忘れないでください

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