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
How to Defend Against Brute-Force and DoS Attacks with Fail2ban, Nginx limit_req, and iptables
In this tutorial, I’ll explain how to protect your public-facing Linux server and Nginx web server from common threats, including brute-force and DoS attacks.
Is Getting AWS Solutions Architect Associate Certification Worth It?
If you are a full-time Software Engineer, there's no strong need to pursue this certification.
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.