且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在同一项目中同时使用AddDbContextFactory()和AddDbContext()扩展方法

更新时间:2022-12-07 19:15:57

它的全部目的在于理解游戏中各种元素的生命周期并正确设置它们.

It is, it's all about understanding the lifetimes of the various elements in play and getting those set correctly.

默认情况下,由 AddDbContextFactory()扩展方法创建的 DbContextFactory 具有Singleton寿命.如果您使用 AddDbContext()扩展方法及其默认设置,它将创建一个 DbContextOptions ,其使用寿命为 Scoped (

By default the DbContextFactory created by the AddDbContextFactory() extension method has a Singleton lifespan. If you use the AddDbContext() extension method with it's default settings it will create a DbContextOptions with a Scoped lifespan (see the source-code here), and as a Singleton can't use something with a shorter Scoped lifespan, an error is thrown.

要解决此问题,我们需要将 DbContextOptions 的寿命也更改为"Singleton".这可以通过显式设置 AddDbContext()

To get round this, we need to change the lifespan of the DbContextOptions to also be 'Singleton'. This can be done using by explicitly setting the scope of the DbContextOptions parameter of AddDbContext()

services.AddDbContext<FusionContext>(options =>
    options.UseSqlServer(YourSqlConnection),
    contextLifetime: ServiceLifetime.Transient, 
    optionsLifetime: ServiceLifetime.Singleton);

在EF核心GitHub存储库上,对此进行了非常好的讨论.同样值得一看的是 DbContextFactory

There's a really good discussion of this on the EF core GitHub repository starting here. It's also well worth having a look at the source-code for DbContextFactory here.

或者,您也可以通过应该像正常情况一样,完全>配置选项DbContext ,因为这些是将在工厂创建的DbContext上设置的选项.

The options should be configured exactly as you would for a normal DbContext as those are the options that will be set on the DbContext the factory creates.