source

'Microsoft' 유형에 대한 서비스를 확인할 수 없습니다.AsNetCore.신원.'AuthController'를 활성화하는 동안 'UserManager'가 발생했습니다.

factcode 2023. 5. 4. 20:36
반응형

'Microsoft' 유형에 대한 서비스를 확인할 수 없습니다.AsNetCore.신원.'AuthController'를 활성화하는 동안 'UserManager'가 발생했습니다.

로그인 컨트롤러에서 이 오류가 발생합니다.

잘못된 작업예외:'Microsoft' 유형에 대한 서비스를 확인할 수 없습니다.AsNetCore.신원.사용자 관리자 1[자동차].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 의 서비스 구성입니다.

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

답을 분명히 하기 위해서입니다.

클래스를 사용하는 경우ApplicationUserstartup.cs 에서:services.AddIdentity<ApplicationUser, IdentityRole>()

그런 다음 주입할 때 컨트롤러에서 동일한 클래스를 사용해야 합니다.

public AccountController(UserManager<ApplicationUser> userManager)

다음과 같은 다른 클래스를 사용하는 경우:

public AccountController(UserManager<IdentityUser> userManager)

그러면 다음 오류가 발생합니다.

잘못된 작업예외:'Microsoft' 유형에 대한 서비스를 확인할 수 없습니다.AsNetCore.신원.사용자 관리자 '1[아이덴티티 사용자]'

당신이 사용했기 때문에ApplicationUser시작할 때, 아님IdentityUser따라서 이 유형은 주입 시스템에 등록되어 있지 않습니다.

이것은 원래 게시물과 약간 관련이 없지만 구글이 당신을 여기로 데려오기 때문에...이 오류가 발생하여 다음을 사용하는 경우:

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

교체해야 합니다.TUser그리고.TRole이러한 기능을 구현하거나 기본값을 사용할 수 있습니다.IdentityUser,IdentityRole

다음과 같이 시작 클래스 내부의 서비스 구성에서 IdentityUser 및 IdentityRole을 개별적으로 설정할 수 있습니다.

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

OR

AddIdentity로 직접 구성할 수 있습니다.

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

서비스 구성에서 역할 관리자를 추가하는 것을 잊지 마십시오.

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

"IdentityServer"를 사용하여 IdentityServer가 사용자를 인증하고 클라이언트를 인증하는 경우.기본적으로 IdentityServer는 실제로 사용자 관리에 관한 것이 아닙니다.그러나 asp.net Identity에 대한 일부 지원이 있습니다.

따라서 다음을 추가해야 합니다.

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

Statup.cs 클래스를 아래와 같이 업데이트해야 합니다.

서비스ID 추가<ApplicationUser,IdentityRole>() .EntityFrameworkStore();

여기: ApplicationUser는 내 사용자 지정 모델 클래스입니다.

저는 도트에서 추가되는 서비스의 순서가 중요했습니다.넷코어 7.

program.cs 의 이 코드로 인해 다음 오류가 발생했습니다.

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddRoles<IdentityRole>();

여기서는 동일한 문이 플립됩니다.이 코드는 정상적으로 작동합니다.

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

위의 답변과 같이 원래 게시물과 조금 관련이 없지만 구글이 당신을 여기로 데려오기 때문에...이 오류가 발생하고 다음을 사용하는 경우 이 방법이 더 간단합니다.

서비스아이덴티티 코어 추가(

위에 나열된 답보다 더 쉬운 해결책이 있습니다.

ApplicationUser라는 사용자 ID 사용자와 ApplicationRole이라는 사용자 역할이 있다고 가정해 보겠습니다. 아래에서 간단히 작업할 수 있습니다.

builder
    .Services
    .AddIdentityCore<ApplicationUser>(identityOptions =>
                                      {
                                          identityOptions.Lockout = new LockoutOptions
                                          {
                                              DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30)
                                              , MaxFailedAccessAttempts = 20
                                          };

                                          identityOptions.Password = new PasswordOptions
                                          {
                                              RequireDigit = true
                                              , RequireLowercase = true
                                              , RequireNonAlphanumeric = true
                                              , RequireUppercase = true
                                              , RequiredLength = 8
                                          };

                                          identityOptions.SignIn = new SignInOptions
                                          {
                                              RequireConfirmedAccount = true
                                              , RequireConfirmedEmail = true
                                          };

                                          identityOptions.User = new UserOptions
                                          {
                                              AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.@1234567890!#$%&'*+-/=?^_`{|}~"
                                              , RequireUniqueEmail = true
                                          };
                                      })
    .AddRoles<ApplicationRole>()
    .AddClaimsPrincipalFactory<UserClaimsPrincipalFactory<ApplicationUser, ApplicationRole>>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

이것이 훨씬 더 간단합니다.

또한 Microsoft 문서에서 DbContext를 그렇게 선언해야 유추할 수 있습니다.

public class ApplicationDbContext
    : IdentityDbContext<ApplicationUser
        , ApplicationRole
        , long
        , ApplicationUserClaim
        , ApplicationUserRole
        , ApplicationUserLogin
        , ApplicationRoleClaim
        , ApplicationUserToken>
{
}

물론 여기서 사용하는 사용자 지정 유형을 사용할 필요는 없으며 기본값 등을 사용할 수 있습니다.

답변과 , 는 위의답비지만슷, 추했다니습야해가저하를 추가해야 했습니다.IUserStore그리고.IRoleStore 유효성 는 "보안 스탬프 유효성 검사"에 대해 합니다.ISystemClock에서 사용 가능)Microsoft.AspNetCore.Authentication 에 있습니다.)가 등록되지 않았으므로 그것도 여기에 있습니다.

아래 유형은 표준 ID 데이터베이스 테이블(dbo)의 이름을 따서 명명됩니다.NetUsers로, dbo.NetRoles 등 )로 지정합니다.Guid아래 유형은 이러한 테이블의 기본 키 유형입니다.으로 이 은 기적으이입니다.string따라서 모델에 맞게 조정합니다.

/* begin services to support app custom identity */

// Add the system clock service
services.AddSingleton<ISystemClock, SystemClock>();

services.TryAddScoped<
    IUserStore<AspNetUser>,
    UserStore<AspNetUser, AspNetRole, ApplicationDbContext, Guid, AspNetUserClaim, AspNetUserRole, AspNetUserLogin, AspNetUserToken, AspNetRoleClaim>>();

services.TryAddScoped<
    IRoleStore<AspNetRole>,
    RoleStore<AspNetRole, ApplicationDbContext, Guid, AspNetUserRole, AspNetRoleClaim>>();

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

/* end services to support app custom identity */

언급URL : https://stackoverflow.com/questions/44483589/unable-to-resolve-service-for-type-microsoft-aspnetcore-identity-usermanager-w

반응형