在Blazor中将标识与AddDbContextFactory一起使用 [英] Using Identity with AddDbContextFactory in Blazor
本文介绍了在Blazor中将标识与AddDbContextFactory一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的Blazor,.Net Core3.1服务器端应用程序中,我最近将EF上下文作用域从瞬态更改为使用工厂扩展,并且运行良好。但是,我将相同的dbcontext工厂代码添加到使用标识的第二个项目&;I在启动时出现异常。
InvalidOperationException: Unable to resolve service for type 'OMS.DALInterfaces.Models.OmsDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9
这在没有使用工厂类时工作正常(即让DI处理OMSDbContext)
services.AddDbContext<OmsDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")),
ServiceLifetime.Transient
);
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<OmsDbContext>();
现在在项目中使用我尝试的身份:
services.AddDbContextFactory<OmsDbContext>(opt =>
opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
.EnableSensitiveDataLogging());
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<OmsDbContext>();
那么在使用Factory Extension时如何在启动时定义标识?
推荐答案
克雷格,帮我们弄清楚了。
在ConfigureServices中,添加DbContext的AddScoped,并使用提供程序从服务中获取工厂。然后,将实例返回给提供程序,如下所示。标识的规范使用Scope,所以我在这里使用Scope。
services.AddDbContextFactory<ApplicationDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
options.EnableSensitiveDataLogging();
});
services.AddScoped<ApplicationDbContext>(p => p.GetRequiredService<IDbContextFactory<ApplicationDbContext>>().CreateDbContext());
这篇关于在Blazor中将标识与AddDbContextFactory一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文