✅ Proper way of using EF DbContext in a BackgroundService
Hello,
The dbContext and the
BackgroundService
have different scopes. I've seen there are 2 solutions.
The possible options are: injecting the IServiceProvider
, or the IServiceScopeFactory
, then manually creating a context.
Which one of the interfaces is better to use? There surely must be some difference...8 Replies
https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/#use-a-dbcontext-factory
any reason you can't use a dbcontextfactory?
That would work, but it's stated there it's for apps that do not create a service scope
Where? Because all I see is
Some application types (e.g. ASP.NET Core Blazor) use dependency injection but do not create a service scope that aligns with the desired DbContext lifetime.
Yes, that part
Then you're misunderstanding what it's saying
All that means is "Use DBContextFactory if what you're injecting it into doesn't match the expected lifetime of a DBContext, but you have to dispose of it yourself"
Thanks, now I get it
this is me