2017-01-28 2 views
1

Я пытаюсь создать логин на основе RefreshFlow sample. У меня есть приложение Angular2. Когда я пытаюсь войти, я получаю следующее сообщение об ошибке:Невозможно разрешить службу для типа OpenIddict.Core.OpenIddictApplicationManager [OpenIddict.Models.OpenIddictApplication] при попытке активировать

An unhandled exception occurred while processing the request. 

InvalidOperationException: Unable to resolve service for type 'OpenIddict.Core.OpenIddictApplicationManager`1[OpenIddict.Models.OpenIddictApplication]' while attempting to activate 'OpPISWeb.Controllers.AuthorizationController'. 
Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired) 

Я использую Javascript services template. Мой запрос: attached file on Github.

Моя конфигурация:

public void ConfigureServices(IServiceCollection services) 
{ 
    try 
    { 
     services.AddMvc(); 

     services.AddEntityFrameworkSqlServer(); 

     services.AddScoped<UserStore<AppUser, AppRole, AppDbContext, int, AppUserClaim, AppUserRole, AppUserLogin, AppUserToken, AppRoleClaim>, AppUserStore>(); 
     services.AddScoped<UserManager<AppUser>, AppUserManager>(); 
     services.AddScoped<RoleManager<AppRole>, AppRoleManager>(); 
     services.AddScoped<SignInManager<AppUser>, AppSignInManager>(); 
     services.AddScoped<RoleStore<AppRole, AppDbContext, int, AppUserRole, AppRoleClaim>, AppRoleStore>(); 

     var connection = Configuration["ConnectionStrings"]; 
     services.AddDbContext<AppDbContext>(options => { 
      options.UseSqlServer(connection); 
      options.UseOpenIddict<int>(); 
     }); 

     services 
      .AddIdentity<AppUser, AppRole>() 
      .AddUserStore<AppUserStore>() 
      .AddUserManager<AppUserManager>() 
      .AddRoleStore<AppRoleStore>() 
      .AddRoleManager<AppRoleManager>() 
      .AddSignInManager<AppSignInManager>() 
      .AddDefaultTokenProviders(); 

     services.AddOpenIddict<int>() 
      .AddEntityFrameworkCoreStores<AppDbContext>() 
      .AddMvcBinders() 
      .EnableTokenEndpoint("/API/authorization/token") 
      .AllowPasswordFlow() 
      .AllowRefreshTokenFlow() 
      .DisableHttpsRequirement(); 

     services.AddSingleton<DbSeeder>(); 

    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.ToString()); 
     throw; 
    } 
} 

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder) 
{ 
    loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
    loggerFactory.AddDebug(); 

    if (env.IsDevelopment()) 
    { 
     app.UseDeveloperExceptionPage(); 
     app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions 
     { 
      HotModuleReplacement = true 
     }); 
    } 
    else 
    { 

    } 

    app.UseStaticFiles(); 

    app.UseIdentity(); 

    app.UseOpenIddict(); 

    app.UseOAuthValidation(); 

    app.UseMvc(); 

    try 
    { 

     dbSeeder.SeedAsync(); 
    } 
    catch (AggregateException e) 
    { 
     throw new Exception(e.ToString()); 
    } 
} 

У меня есть пользовательские классы Идентичность и магазины:

[Table("Roles")] 
    public partial class AppRole : IdentityRole<int, AppUserRole, AppRoleClaim> 
    { 
     public AppRole() { } 
     public AppRole(string role) : base(role) { } 
    } 

    [Table("Users")] 
    public partial class AppUser : IdentityUser<int, AppUserClaim, AppUserRole, AppUserLogin> 
    { 
    } 

public partial class AppUserClaim : IdentityUserClaim<int> 

... 

public partial class AppDbContext : IdentityDbContext<AppUser, AppRole, int, AppUserClaim, AppUserRole, AppUserLogin, AppRoleClaim, AppUserToken> 


    public class AppRoleManager : RoleManager<AppRole> 
    { 
     public AppRoleManager(IRoleStore<AppRole> store, IEnumerable<IRoleValidator<AppRole>> roleValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, ILogger<RoleManager<AppRole>> logger, IHttpContextAccessor contextAccessor) : base(store, roleValidators, keyNormalizer, errors, logger, contextAccessor) 
     { 
     } 
    } 
    public class AppRoleStore : RoleStore<AppRole, AppDbContext, int, AppUserRole, AppRoleClaim> 
    { 
     public AppRoleStore(AppDbContext context, IdentityErrorDescriber describer = null) : base(context, describer) 
     { 
     } 

     protected override AppRoleClaim CreateRoleClaim(AppRole role, Claim claim) 
     { 
      return new AppRoleClaim(role, claim); 
     } 
    } 
    public class AppSignInManager : SignInManager<AppUser> 
    { 
     public AppSignInManager(UserManager<AppUser> userManager, IHttpContextAccessor contextAccessor, IUserClaimsPrincipalFactory<AppUser> claimsFactory, IOptions<IdentityOptions> optionsAccessor, ILogger<SignInManager<AppUser>> logger) : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger) 
     { 
     } 
    } 
    public class AppUserManager : UserManager<AppUser> 
    { 
     public AppUserManager(IUserStore<AppUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<AppUser> passwordHasher, IEnumerable<IUserValidator<AppUser>> userValidators, IEnumerable<IPasswordValidator<AppUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<AppUser>> logger) : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger) 
     { 
     } 
    } 
    public class AppUserStore : UserStore<AppUser, AppRole, AppDbContext, int, AppUserClaim, AppUserRole, AppUserLogin, AppUserToken, AppRoleClaim> 
    { 
     public AppUserStore(AppDbContext context, IdentityErrorDescriber describer = null) : base(context, describer) 
     { 
     } 

     protected override AppUserClaim CreateUserClaim(AppUser user, Claim claim) 
     { 
      return new AppUserClaim(user, claim); 
     } 

     protected override AppUserLogin CreateUserLogin(AppUser user, UserLoginInfo login) 
     { 
      return new AppUserLogin(user, login); 
     } 

     protected override AppUserRole CreateUserRole(AppUser user, AppRole role) 
     {    
      return new AppUserRole(user, role); 
     } 

     protected override AppUserToken CreateUserToken(AppUser user, string loginProvider, string name, string value) 
     { 
      return new AppUserToken(user, loginProvider, name, value); 
     } 
    } 

Контроллер:

public class AuthorizationController : Controller 
//... 

[HttpPost("token"), Produces("application/json")] 
     public async Task<IActionResult> Exchange(OpenIdConnectRequest request) 
     { 
      Debug.Assert(request.IsTokenRequest(), 
       "The OpenIddict binder for ASP.NET Core MVC is not registered. " + 
       "Make sure services.AddOpenIddict().AddMvcBinders() is correctly called."); 
//.... 

Я действительно надеюсь, что кто-то может мне точку в правильном направлении. Я в отчаянии. Спасибо.

+0

Я имею вопрос здесь и мой набор вверх так очень близко к тому, что вы здесь .. я отправляюсь некоторые, где и я не могу поставить свою фигуру на ней, потому что я просто держать удар 'Дополнительная информация: Невозможно создать экземпляр типа реализации «foo.Models.User.AppRoleStore» для типа службы «Microsoft.AspNetCore.Identity.IRoleStore'1 [foo.Models.User.AppRoles]». '.. у вас есть репо или что-то, что я могу пересечь проверить? Он очень похож на одну из проблем github, поэтому я решил попробовать LOL. –

+0

@ jeremy.bass К сожалению, нет. Мое приложение является частным и на данный момент очень большим. Даже если я расскажу об этом, вам будет очень сложно понять, как это сделать. Он разделен на несколько библиотек, классов ... – Makla

ответ

2

Поскольку вы используете собственный тип ключа (int), убедитесь, что вы также используете правильный объект: OpenIddictApplication<int> (вместо OpenIddictApplication).

OpenIddictApplicationManager<OpenIddictApplication> 

--> 

OpenIddictApplicationManager<OpenIddictApplication<int>> 
Смежные вопросы