在Identity Asp.net core 3 MVC中创建服务IUserStore时出错 [英] Error in Service IUserStore being created in Identity Asp.net core 3 MVC

查看:241
本文介绍了在Identity Asp.net core 3 MVC中创建服务IUserStore时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新

请参阅下面的更新.

我最近问过一个上一个stackoverflow问题,但是从以下两个地方实施建议的解决方案后,我遇到一个问题:用于ASP.NET Core身份的自定义存储提供程序.我只是无法获得解决方案.我已经按照建议实现了IdentityUser的扩展名和IdentityRole的扩展名.我已经为UserStore实现了IUserPasswordStoreIUserRoleStoreIUserStore,并且我已经为RoleStore实现了IRoleStore.我还实现了新的实现IdentityDbContext的dbContext ApplicationDbContext.由于构造函数不接受参数,因此出现了问题,因此我实现了一个新的构造函数.我不确定这是否正确.

I have asked a previous stackoverflow question very recently, but I face an issue after implementing the suggested solutions from the following 2 places Identity model customization in ASP.NET Core and Custom storage providers for ASP.NET Core Identity. I am just not able to get the solution to work. I have implemented the extension of IdentityUser as recommended and the extension of IdentityRole. I have implemented IUserPasswordStore and IUserRoleStore and IUserStore for UserStore and I have implemented IRoleStore for RoleStore. I have also implemented the new dbContext ApplicationDbContext which implements IdentityDbContext. There was an issue with this with the constructor not accepting a parameter so I implemented a new constructor. I am not sure if this is right.

但这似乎无关紧要,因为在调用

However that appears to be irrelevant because I get the error in the Main method of Program.cs when calling

CreateHostBuilder(args).Build().Run(); 

而且错误很大.我把它放在最后.在线搜索错误的各个部分并没有提供有关我在做什么的任何想法,并且由于我是ASP.NET Core 3和Identity的新手,所以感到很困惑.

And the error is massive. I have placed it at the end. Searching the parts of the error online does not provide any ideas as to what I am doing, and as I am new to ASP.NET Core 3 and Identity I am stumped.

这是我到目前为止的代码.

Here is the code I have so far.

ConfigureServices 方法

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddMvc(options =>
        {
            var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        options.EnableEndpointRouting = false;
        });

        services.AddDbContext<EntitiesModel>(options => options.UseSqlServer(
            Configuration["Data:ConnectionStrings:XXXXDbConnection"]));
        services.AddIdentity<UserViewModel,RoleViewModel>().AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders().AddRoles<RoleViewModel>(); ;
        services.AddTransient<IUserStore<UserViewModel>, UserStore>();
        services.AddTransient<IRoleStore<RoleViewModel>, RoleStore>();
        services.ConfigureApplicationCookie(options =>
        {
            options.LoginPath = "/Login";
            options.LogoutPath = "/Logout";
        });
    }

ApplicationDbContext -这些都在同一个命名空间中

ApplicationDbContext - these are all in the same namespace

public class IdentityDbContext
    : IdentityDbContext<IdentityUser, IdentityRole, string>
{
    public IdentityDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }
}

public class IdentityDbContext<TUser>
    : IdentityDbContext<TUser, IdentityRole, string>
    where TUser : IdentityUser
{
    public IdentityDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }
}

// Uses the built-in Identity types except with custom User and Role types
// The key type is defined by TKey
public class IdentityDbContext<TUser, TRole, TKey> : IdentityDbContext<
    TUser, TRole, TKey, IdentityUserClaim<TKey>, IdentityUserRole<TKey>,
    IdentityUserLogin<TKey>, IdentityRoleClaim<TKey>, IdentityUserToken<TKey>>
    where TUser : IdentityUser<TKey>
    where TRole : IdentityRole<TKey>
    where TKey : IEquatable<TKey>
{
    private DbContextOptions<ApplicationDbContext> options;
    //private string nameOrConnectionString;

    public IdentityDbContext(DbContextOptions<ApplicationDbContext> options)
    {
        this.options = options;
    }

}

public abstract class IdentityDbContext<
        TUser, TRole, TKey, TUserClaim, TUserRole, TUserLogin, TRoleClaim, TUserToken>
    : IdentityUserContext<TUser, TKey>
    where TUser : IdentityUser<TKey>
    where TRole : IdentityRole<TKey>
    where TKey : IEquatable<TKey>
    where TUserRole : IdentityUserRole<TKey>
{

}
public class ApplicationDbContext : IdentityDbContext<UserViewModel,RoleViewModel,int>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<UserViewModel>(b =>
        {               
            b.HasMany(e => e.UserRoles)
                .WithOne()
                .HasForeignKey(ur => ur.Id)
                .IsRequired();
        });
        modelBuilder.Entity<UserViewModel>(b =>
        {
            b.ToTable("T_CustomerContacts");
        });
        modelBuilder.Entity<RoleViewModel>(b =>
        {
            b.ToTable("T_LoginRoles");
        });
        modelBuilder.Entity<UserRoleViewModel>(b =>
        {
            b.ToTable("T_CustomerContactRole");
        });         
        modelBuilder.Entity<RoleViewModel>(b =>
        {
            b.HasMany(e => e.UserRoles)
                .WithOne(e => e.Role)
                .HasForeignKey(ur => ur.RoleId)
                .IsRequired();
        });
    }
}

UserViewModel

public class UserViewModel : IdentityUser<int>
{

UserRoleViewModel

public class UserRoleViewModel : IdentityUserRole<int>
{

RoleViewModel

public class RoleViewModel : IdentityRole<int>
{   

RoleStore

public class RoleStore : IRoleStore<RoleViewModel>
{

UserStore

public class UserStore : IUserStore<UserViewModel>, IUserPasswordStore<UserViewModel>, IUserRoleStore<UserRoleViewModel>
{

我必须补充一点,这是我尝试过的最终配置.我尝试了许多组合和解决方案. 部分错误如下

I have to add that this is the final configuration I have tried. I have tried many combinations and solutions. Part of the error is as follows

启动应用程序时发生错误. AggregateException:无法构造某些服务(验证服务描述符'ServiceType:Microsoft.AspNetCore.Identity.IUserStore 1[TrussCorp.CustomerPortal.Models.ViewModel.Identity.UserViewModel] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore 4 [TrussCorp.CustomerPortal.Models.ViewModel.Identity.UserViewModel,TrussCorp.CustomerPortal.Models.时出错. ViewModel.Identity.RoleViewModel,TrussCorp.CustomerPortal.Models.ViewModel.Identity.ApplicationDbContext,System.Int32]':尝试激活"Microsoft"时,无法解析类型为"TrussCorp.CustomerPortal.Models.ViewModel.Identity.ApplicationDbContext"的服务. AspNetCore.Identity.EntityFrameworkCore.UserStore 4[TrussCorp.CustomerPortal.Models.ViewModel.Identity.UserViewModel,TrussCorp.CustomerPortal.Models.ViewModel.Identity.RoleViewModel,TrussCorp.CustomerPortal.Models.ViewModel.Identity.ApplicationDbContext,System.Int32]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.IRoleStore 1 [TrussCorp.CustomerPortal.Models.ViewModel.Identity.RoleViewModel]寿命:范围内的实现类型:Microsoft.AspNetCore.Identity.EntityFrameworkCore.RoleStore 3[TrussCorp.CustomerPortal.Models.ViewModel.Identity.RoleViewModel,TrussCorp.CustomerPortal.Models.ViewModel.Identity.ApplicationDbContext,System.Int32]': Unable to resolve service for type 'TrussCorp.CustomerPortal.Models.ViewModel.Identity.ApplicationDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.RoleStore 3 [TrussCorp.CustomerPortal.Models.Views .Identity.RoleViewModel,TrussCorp.CustomerPortal.Models.ViewModel.Identity.ApplicationDbContext,System.Int32]".) Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable serviceDescriptors,ServiceProviderOptions选项)

An error occurred while starting the application. AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.IUserStore1[TrussCorp.CustomerPortal.Models.ViewModel.Identity.UserViewModel] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore4[TrussCorp.CustomerPortal.Models.ViewModel.Identity.UserViewModel,TrussCorp.CustomerPortal.Models.ViewModel.Identity.RoleViewModel,TrussCorp.CustomerPortal.Models.ViewModel.Identity.ApplicationDbContext,System.Int32]': Unable to resolve service for type 'TrussCorp.CustomerPortal.Models.ViewModel.Identity.ApplicationDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore4[TrussCorp.CustomerPortal.Models.ViewModel.Identity.UserViewModel,TrussCorp.CustomerPortal.Models.ViewModel.Identity.RoleViewModel,TrussCorp.CustomerPortal.Models.ViewModel.Identity.ApplicationDbContext,System.Int32]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.IRoleStore1[TrussCorp.CustomerPortal.Models.ViewModel.Identity.RoleViewModel] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.EntityFrameworkCore.RoleStore3[TrussCorp.CustomerPortal.Models.ViewModel.Identity.RoleViewModel,TrussCorp.CustomerPortal.Models.ViewModel.Identity.ApplicationDbContext,System.Int32]': Unable to resolve service for type 'TrussCorp.CustomerPortal.Models.ViewModel.Identity.ApplicationDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.RoleStore3[TrussCorp.CustomerPortal.Models.ViewModel.Identity.RoleViewModel,TrussCorp.CustomerPortal.Models.ViewModel.Identity.ApplicationDbContext,System.Int32]'.) Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable serviceDescriptors, ServiceProviderOptions options)

更新

我回到了上一个问题的开头,但是通过反转以下命令的顺序解决了上面的错误

I am back to where I began with the previous question and but solved the above error by reversing the orders of the following

    services.AddTransient<IUserStore<UserViewModel>, UserStore>();
        services.AddTransient<IRoleStore<RoleViewModel>, TrussCorp.CustomerPortal.Identity.RoleStore>();
        services.AddIdentity<UserViewModel,RoleViewModel>().AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders().AddRoles<RoleViewModel>();

但是,正如现在所说,我得到的是 Store没有实现IUserRoleStore UserManager.GetUserRoleStore ()错误使我回到第一个平方.

But as stated now I am getting Store does not implement IUserRoleStore UserManager.GetUserRoleStore() error which has put me back to square one.

推荐答案

我对其他开发人员的建议是,如果您在互联网上找不到类似的问题,那说明您在做些愚蠢而独特的事情.

My advice to other Developers is if you can not find a similar problem on the internet, you are doing something silly and unique.

解决方案是更改此

public class UserStore : IUserStore<UserViewModel>, IUserPasswordStore<UserViewModel>, IUserRoleStore<UserRoleViewModel>
{

对此

public class UserStore : IUserStore<UserViewModel>, IUserPasswordStore<UserViewModel>, IUserRoleStore<UserViewModel>
{

这篇关于在Identity Asp.net core 3 MVC中创建服务IUserStore时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆