ASP.NET Core 2 – 身份 – 自定义角色的DI错误

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

services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity() .AddEntityFrameworkStores() .AddDefaultTokenProviders(); 

在同一个文件中,我还用app.UseAuthentication();替换了service.UseIdentity() app.UseAuthentication(); 正如MS在新版ASP Core 2中所推荐的那样。

我的Db背景:

  public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext(DbContextOptions 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 { get; set; } //public DbSet ApplicationRole { get; set; } } 

我的自定义Role类:

  public class ApplicationRole : IdentityRole { public ApplicationRole() : base() { } public ApplicationRole(string roleName) : base(roleName) { } public bool IsDefault { get; set; } } 

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

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

这一切都运行正常,但自从VS 2017更新到最新版本并安装.NET Core 2.0后,最后一行代码现在抛出以下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= 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:\gsandorx\Documents\Visual Studio 2017\Projects\CspLicensingPortal\CspLicensingPortal\Startup.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。

有任何想法吗?

您必须自己创建IServiceScope。

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

 var roleManager = serviceProvider.GetService>(); 

 IServiceScopeFactory scopeFactory = app.ApplicationServices.GetRequiredService(); using (IServiceScope scope = scopeFactory.CreateScope()) { RoleManager roleManager = scope.ServiceProvider.GetRequiredService>(); // Seed database code goes here }