ASP.NET Core 2 - 身份 - 自定义角色的 DI 错误 [英] ASP.NET Core 2 - Identity - DI errors with custom Roles

查看:20
本文介绍了ASP.NET Core 2 - 身份 - 自定义角色的 DI 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Startup.cs 中得到了这个代码:

I got this code in my Startup.cs:

 services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

在同一个文件中,我还将 service.UseIdentity() 替换为 app.UseAuthentication(); 作为 MS 在新版本 ASP Core 2 中推荐的.

In that same file, I also replaced the service.UseIdentity() with app.UseAuthentication(); as recommended by MS in the new version of ASP Core 2.

我的数据库上下文:

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

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }


    //public DbSet<ApplicationUser> ApplicationUser { get; set; }

    //public DbSet<ApplicationRole> ApplicationRole { get; set; }
}

还有我的自定义角色类:

And my custom Role class:

 public class ApplicationRole : IdentityRole
{
    public ApplicationRole() : base() { }

    public ApplicationRole(string roleName) : base(roleName) { }

    public bool IsDefault { get; set; }
}

在运行应用程序时,我得到了一个运行的 SeedDatabase 辅助方法:

When running the application, I got a SeedDatabase helper method that runs:

var roleManager = serviceProvider.GetService<RoleManager<ApplicationRole>>();

这一切正常,但自从将 VS 2017 更新到最新版本并安装 .NET Core 2.0 后,这最后一行代码现在抛出以下异常:

This was all working fine, but since updating VS 2017 to the lastest version and installing .NET Core 2.0, this last line of code now throws the following exception:

System.AggregateException occurred
HResult=0x80131500
Message=One or more errors occurred. (Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.RoleManager`1[CspLicensingPortal.Models.ApplicationRole]' from root provider.)
Source=<Cannot evaluate the exception source>
StackTrace:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at CspLicensingPortal.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) in D:gsandorxDocumentsVisual Studio 2017ProjectsCspLicensingPortalCspLicensingPortalStartup.cs:line 275

Inner Exception 1:
InvalidOperationException: Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.RoleManager`1[MyApplication.Models.ApplicationRole]' from root provider.

我不确定为什么 DI 服务管理器无法再找到我的 ApplicationRole 类.我已经检查过并且我所有的引用都使用这个类而不是默认的 IdentityRole.

I'm not sure why the DI service manager is no longer able to find my ApplicationRole class. I have checked and all my references are using this class and not the default IdentityRole.

有什么想法吗?

推荐答案

您必须自己创建 IServiceScope.

You have to create the IServiceScope on your own.

要做到这一点,你必须替换

To do this you have to replace

var roleManager = serviceProvider.GetService<RoleManager<ApplicationRole>>();

using (IServiceScope scope = app.ApplicationServices.CreateScope()) {
    RoleManager<IdentityRole> roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();

    // Seed database code goes here
}

这篇关于ASP.NET Core 2 - 身份 - 自定义角色的 DI 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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