C
C#3d ago
Core

✅ 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
Core
CoreOP3d ago
That would work, but it's stated there it's for apps that do not create a service scope
Keswiik
Keswiik3d ago
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.
Core
CoreOP3d ago
Yes, that part
Keswiik
Keswiik3d ago
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"
Core
CoreOP3d ago
Thanks, now I get it
Core
CoreOP3d ago
this is me

Did you find this page helpful?