Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ErikEJ opened this issue Feb 21, 2024 · 2 comments
Milestone

Comments

@ErikEJ
Copy link
Contributor

ErikEJ commented Feb 21, 2024

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

@k-basant
Copy link

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
Copy link
Member

@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 ajcvickers added this to the Backlog milestone Mar 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants