© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
17 replies
alkasel#159

EF Core .NET 6 - Access DbContext from singleton service

Hi,
I've started using EF Core (.NET 6) since a few weeks, but I'm a bit confused about the following aspects:
- I keep reading the dbContext should be scoped, and that make sense.
- If I want service A to access dbContext, service A needs to be scoped as well, it cannot be a singleton. And I could understand this: since a service in injected in the constructor, A needs to be re-instantiated every time it needs to access dbContext so that each time a new instance of dbContext is injected into it
- Controllers are transient (or scoped, not sure), so when a request come, the controller is instantiated passing to it a service A instance which in turn is instantiated on the fly passing an instance of dbcontext to it.

Until here everything makes sense.

I have a scenario where I have a long-running task (singleton service B) that periodically needs to write data to the database. How am I supposed to do this, since I cannot inject scoped service A into singleton service B?

From this post https://stackoverflow.com/a/58989132/7035167 it seems like I should have a factory of service A objects and, everytime B needs to access database, I should generate an instance of A, use it to write on database and then dispose it.
However it seems to me that this defeats the whole purpose of the dependency injection concept: from what I've understood, I should not instantiate an object that is injected somewhere else. Furthermore, if I was to instantiate service A, I should first instantiate dbContext too, and I think this is not the correct way of doing things.
Stack Overflow
Use DbContext in ASP .Net Singleton Injected Class
I need to access my database in a Singleton class instantiated in my Startup class. It seems that injecting it directly results in a DbContext that is disposed.

I get the following error:
Cannot
Use DbContext in ASP .Net Singleton Injected Class
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources
Was this page helpful?

Similar Threads

Recent Announcements

Similar Threads

.NET Core DBContext
C#CC# / help
2w ago
❔ Singleton/semaphor EF Core
C#CC# / help
3y ago
✅ EF Core, Proper DbContext Instantiation
C#CC# / help
3y ago
❔ .NET CORE 6 services
C#CC# / help
4y ago