EntityFramework.Docs
EntityFramework.Docs copied to clipboard
DbContext lifetime with ASP.NET Core hosted service (or other "background" process)
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
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.
@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.