[英]ASP.NET Core 2 - Identity - DI errors with custom Roles
我在Startup.cs中得到了這段代碼:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
在同一個文件中,我還用app.UseAuthentication();
替換了service.UseIdentity()
app.UseAuthentication();
正如MS在新版ASP Core 2中所推薦的那樣。
我的Db背景:
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; }
}
我的自定義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<ApplicationRole>>();
這一切都運行良好,但自從VS 2017更新到最新版本並安裝.NET Core 2.0后,最后一行代碼現在拋出以下異常:
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:\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<RoleManager<ApplicationRole>>();
同
using (IServiceScope scope = app.ApplicationServices.CreateScope()) {
RoleManager<IdentityRole> roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
// Seed database code goes here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.