EntityFramework.Docs icon indicating copy to clipboard operation
EntityFramework.Docs copied to clipboard

DbContext lifetime with ASP.NET Core hosted service (or other "background" process)

Open ErikEJ opened this issue 1 year ago • 2 comments

Type of issue

Missing information

Description

Looking through the lifetime docs here - is it OK to use both AddDbContext and AddDbContextFactory DI registrations in the same ASP.NET Core app??

There is a lot of talk about Blazor, but I have never worked with Blazor (and I imagine maybe others wont have)

  • AddDbContext for injecting in controllers/minimal API handlers
  • AddDbContextFactory for injecting in background services (using dispose pattern)

Page URL

https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/

Content source URL

https://github.com/dotnet/EntityFramework.Docs/blob/main/entity-framework/core/dbcontext-configuration/index.md

Document Version Independent Id

b0a3d5ad-b62c-1ff4-386a-f11e350eea0c

Article author

@ajcvickers

ErikEJ avatar Feb 21 '24 12:02 ErikEJ

is it OK to use both AddDbContext and AddDbContextFactory DI registrations in the same ASP.NET Core app??

  • AddDbContext for injecting in controllers/minimal API handlers
  • AddDbContextFactory for injecting in background services (using dispose pattern)

IMO this should be fine as Factory is by default registered as a singleton (refer here) and manages instances of DbContext in isolation with that of DbContext instance(s) managed by the application's DI Container.

k-basant avatar Mar 10 '24 08:03 k-basant

@ErikEJ Sorry for the slow response. I think this should be fine, but I'd need to play with things a bit to be completely sure.

ajcvickers avatar Mar 10 '24 11:03 ajcvickers