C# DbContext ServiceLifeTime
- Categories:
- notes
In .NET Core, we can control the lifetime of our services, including DbContext
, by specifying the appropriate ServiceLifetime
. The choice of service lifetime depends on application’s requirements.
Here are some common service lifetimes and when to use them:
Transient: A new instance of the service is created every time it’s requested. This is suitable for stateless services or services that have a very short lifespan.
Scoped: A single instance of the service is created for each HTTP request. Scoped services are suitable for scenarios where you want to share the same instance of a service within the scope of a single request. In ASP.NET Core, this is often used for
DbContext
instances in a web application. Each HTTP request gets its ownDbContext
, and theDbContext
is disposed at the end of the request.Singleton: A single instance of the service is created for the lifetime of the application. This is suitable for stateless services that can be reused across all requests.
I only have experience with C# Worker service to consume messsage from a queue. For DbContext
instances, I usually choose Transient
because my C# worker working independently with each message.
When using Transient lifetime, a new instance of the DbContext will be created for each operation, ensuring that each message is handled in isolation without sharing the same DbContext instance across messages.
Here’s an example of registering a scoped DbContext
in .NET Core Program.cs
:
- Tags:
- #c sharp
Recent Posts
DevSecOps
My Notes about DevSecOps
AWS Secrets Manager
Explanation about AWS Secrets Manager with example code.
Envelope Encryption
Envelope encryption is the practice of encrypting plaintext data with a data key, and then encrypting the data key under another key.
Tutorial - "su username vs su - username" - A Security Perspective
The main difference between `su username` and `su - username` lies in the environment variables that are loaded when switching to the specified user.
Subdomain Hijacking
My dormant subdomain was recently hijacked, redirecting it to a online gamble registration page.