我正在尝试使用新的 DbContextFactory
the DbContext configuration section of the EF Core docs 中讨论的模式.
我有 DbContextFactory
在我的 Blazor 应用程序中成功启动并运行,但我想保留注入(inject) DbContext
实例的选项直接为了保持我现有的代码正常工作。
但是,当我尝试这样做时,出现以下错误:
System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.EntityFrameworkCore.IDbContextFactory
1[MyContext] Lifetime: Singleton ImplementationType: Microsoft.EntityFrameworkCore.Internal.DbContextFactory
1[MyContext]': Cannot consume scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions1[MyContext]' from singleton 'Microsoft.EntityFrameworkCore.IDbContextFactory
1[MyContext]'.) ---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: Microsoft.EntityFrameworkCore.IDbContextFactory1[MyContext] Lifetime: Singleton ImplementationType: Microsoft.EntityFrameworkCore.Internal.DbContextFactory
1[MyContext]': Cannot consume scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions1[MyContext]' from singleton 'Microsoft.EntityFrameworkCore.IDbContextFactory
1[MyContext]'. ---> System.InvalidOperationException: Cannot consume scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions1[MyContext]' from singleton 'Microsoft.EntityFrameworkCore.IDbContextFactory
1[MyContext]'.
我在试验时也设法得到了这个错误:
Cannot resolve scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions`1[MyContext]' from root provider.
理论上是否可以同时使用
AddDbContext
和 AddDbContextFactory
一起?
最佳答案
是的,这一切都是为了了解游戏中各种元素的生命周期并正确设置它们。
默认情况下 DbContextFactory
由 AddDbContextFactory()
创建扩展方法有一个 Singleton 生命周期。如果您使用 AddDbContext()
使用默认设置的扩展方法将创建一个 DbContextOptions
与 Scoped
生命周期 ( see the source-code here ),并作为 Singleton
不能使用较短的 Scoped
生命周期,抛出错误。
为了解决这个问题,我们需要更改 DbContextOptions
的生命周期。也成为“单例”。这可以通过显式设置 DbContextOptions
的范围来完成。 AddDbContext()
的参数
services.AddDbContext<FusionContext>(options =>
options.UseSqlServer(YourSqlConnection),
contextLifetime: ServiceLifetime.Transient,
optionsLifetime: ServiceLifetime.Singleton);
有一个很好的讨论 on the EF core GitHub repository starting here .还值得一看 DbContextFactory
的源代码here .或者,您也可以更改
DbContextFactory
的生命周期。由 setting the ServiceLifetime parameter in the constructor :services.AddDbContextFactory<FusionContext>(options =>
options.UseSqlServer(YourSqlConnection),
ServiceLifetime.Scoped);
选项应准确配置as you would for a normal DbContext因为这些是将在工厂创建的 DbContext 上设置的选项。
关于c# - 在同一个项目中同时使用 AddDbContextFactory() 和 AddDbContext() 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65022729/