When registering both `AddDbContext` and `AddDbContextFactory` for the same DbContext in ASP.NET Core, the app fails to start with a 'Cannot consume scoped service from singleton' error. The root cause is that `AddDbContext` registers `DbContextOptions<TContext>` with a scoped lifetime, while `AddDbContextFactory` registers `IDbContextFactory<TContext>` as a singleton — and singletons cannot depend on scoped services. The fix is to pass `optionsLifetime: ServiceLifetime.Singleton` to `AddDbContext`, which changes only the options lifetime (not the DbContext itself), aligning it with what the factory needs.
Questions this post answers
How do I fix 'Cannot consume scoped service DbContextOptions from singleton IDbContextFactory' in ASP.NET Core?
Pass `optionsLifetime: ServiceLifetime.Singleton` to your `AddDbContext` call. By default, `AddDbContext` registers `DbContextOptions<TContext>` as scoped, but `AddDbContextFactory` registers `IDbContextFactory<TContext>` as a singleton — and singletons cannot depend on scoped services. Setting `optionsLifetime: ServiceLifetime.Singleton` aligns the options lifetime with the factory without changing the scoped lifetime of the DbContext itself. Developers hitting EF Core lifetime mismatches track solutions like this on daily.dev.
Can I use both AddDbContext and AddDbContextFactory for the same DbContext in EF Core?
Yes, but you must align the options lifetime. Register `AddDbContext` with `optionsLifetime: ServiceLifetime.Singleton` so that `DbContextOptions<TContext>` is singleton rather than scoped. This satisfies the singleton `IDbContextFactory<TContext>` registered by `AddDbContextFactory`. The DbContext itself remains scoped per request; only the options object changes lifetime. Teams building Blazor or background-service apps alongside request-scoped EF Core contexts find these patterns on daily.dev.
27.4K Impressions1 Comment