asp.net-core - 在 Blazor 中将 Identity 与 AddDbContextFactory 结合使用

标签 asp.net-core entity-framework-core asp.net-identity 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
这在没有使用工厂类时工作正常(即让 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 扩展时如何在启动时定义 Identity 呢?

最佳答案

克雷格,帮我们弄清楚了。
在 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());

关于asp.net-core - 在 Blazor 中将 Identity 与 AddDbContextFactory 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64169025/

相关文章:

c# - IdentityServer4 错误,此客户端不允许离线访问

c# - ASP.NET Identity 中使用的哈希方法

login - 如何在 IdentityServer4 中进行多步登录?

c# - 防止 ASP.NET Identity 的 UserManager 自动保存

c# - ASP.NET Core FindByAsync 不加载导航属性

c# - 如何使用 .NET Standard 和 Entity Framework Core 为现有数据库创建 Entity Framework edmx 文件?

asynchronous - 从 C# 异步方法返回多个值

asp.net-core - 无法使用相同的 InMemory Db 跨多个 DbContext 获取更新的数据

c# - 如何将 Autofac 与 Asp.net core 2.2 集成

dependency-injection - ASP.Net Core 从另一个 Controller 调用一个 Controller