在 Blazor 中将 Identity 与 AddDbContextFactory 结合使用

Cra*_*aig 4 asp.net-identity entity-framework-core asp.net-core blazor blazor-server-side

在我的 Blazor .Net Core 3.1 服务器端应用程序中,我最近将 EF 内容范围从临时更改为使用工厂扩展,并且运行良好。但是,我将相同的 dbcontext 工厂代码添加到使用 Identity 的第二个项目中,并且在启动时出现异常。

InvalidOperationException: Unable to resolve service for type 'OMS.DALInterfaces.Models.OmsDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9
Run Code Online (Sandbox Code Playgroud)

这在没有使用工厂类时工作正常(即让 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>();
Run Code Online (Sandbox Code Playgroud)

现在在使用身份的项目中我尝试过:

services.AddDbContextFactory<OmsDbContext>(opt =>
                opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
                .EnableSensitiveDataLogging());

services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<OmsDbContext>();
Run Code Online (Sandbox Code Playgroud)

那么在使用Factory扩展时如何在启动时定义Identity呢?

小智 13

克雷格,帮我们弄清楚了。

在 ConfigureServices 中,DbContext 的 AddScoped 并使用提供程序从服务中获取工厂。然后,将实例返回给提供者,如下所示。Identity 的规范使用 scoped 所以我在这里使用 scoped。

        services.AddDbContextFactory<ApplicationDbContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            options.EnableSensitiveDataLogging();
        });

        services.AddScoped<ApplicationDbContext>(p => p.GetRequiredService<IDbContextFactory<ApplicationDbContext>>().CreateDbContext());
Run Code Online (Sandbox Code Playgroud)