When building modern ASP.NET Core applications, managing service lifetimes is essential for memory management, performance, and thread safety.
Let's break down the three types of lifetimes: Scoped, Singleton, and Transient — with visual clarity, real-life examples, and proper code usage.
1.Scoped Services
- A single instance is created per HTTP request (or per scope in non-web apps).
- Suitable for services that work with a single request's data, like Entity Framework's DbContext.
Example
In the case of handling user authentication, a Scoped service like AuthService is created once per user request to manage login, logout, and token refresh, ensuring it operates within the scope of that particular HTTP request.
2.Singleton Services
- Created once and shared throughout the application's lifetime.
- Must be thread-safe, since it is shared across multiple requests and threads.
Example
In the case of password hashing during user registration or login, a Transient service like PasswordHasher is instantiated each time to securely hash passwords with a unique salt, providing a fresh instance for each hashing operation.
3.Transient Services
- A new instance is created each time the service is requested.
- Ideal for stateless operations or services that do not need to maintain any state.
Example
In the case of user authorization, a Singleton service like JwtTokenValidator is used to parse and validate JWT tokens efficiently across all requests without creating multiple instances.
Scoped vs Singleton vs Transient
Singleton: A single instance is created and shared throughout the application's lifetime. Ideal for shared, stateless services.
Scoped: A new instance is created per HTTP request. Useful when you want to maintain state within a single request, like with DbContext.
Transient: A new instance is provided every time the service is requested. Suitable for lightweight, short-lived operations.
Conclusion
Understanding service lifetimes helps in avoiding memory leaks, ensuring thread safety, and improving performance.
- Scoped for per-request logic like DbContext
- Singleton for app-wide shared logic
- Transient for short-lived, one-time tasks
Top comments (1)
This is really useful 🔥