dotnet / EntityFramework.Docs

Documentation for Entity Framework Core and Entity Framework 6
https://docs.microsoft.com/ef/
Creative Commons Attribution 4.0 International
1.59k stars 1.95k forks source link

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

Open ErikEJ opened 3 months ago

ErikEJ commented 3 months ago

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)

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

k-basant commented 3 months ago

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.

ajcvickers commented 3 months ago

@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.