Here is the clearest real-time explanation of when to use
AddSingleton, AddScoped, and AddTransient — with practical scenarios you can give directly in interviews.
✅ Real-Time Scenarios for AddSingleton, AddScoped, AddTransient
π¦ 1. AddSingleton — One instance for the entire application
✔ Real-Time Scenarios
Use Singleton when the data is shared and does NOT change per request.
Examples
a) Caching data
services.AddSingleton<ICacheService, MemoryCacheService>();
-
Stores frequently used data (e.g., reference data, master data)
b) Configuration / settings
services.AddSingleton<IConfigProvider, ConfigProvider>();
c) Logging service
services.AddSingleton<ILoggerService, LoggerService>();
d) Background job manager
-
Quartz scheduler
-
Hangfire manager
✔ When to use:
-
When service is stateless
-
When service is thread-safe
-
When you want performance improvements
π© 2. AddScoped — One instance per HTTP request
✔ Real-Time Scenarios
Use Scoped for things that should be unique per request (API call).
Examples
a) DbContext
services.AddScoped<AppDbContext>();
Each request gets a new DbContext → avoids cross-request data issues.
b) Repository services
services.AddScoped<IUserRepository, UserRepository>();
c) Business services
Example: OrderService, ProductService, UserService
✔ When to use:
-
Anything that works with database
-
Per-request logic (validation, authentication)
-
Services that should not share state across users
π₯ 3. AddTransient — New instance every time it is requested
✔ Real-Time Scenarios
Use Transient for lightweight, stateless objects.
Examples
a) Utility classes
services.AddTransient<IEmailFormatter, EmailFormatter>();
b) Helper classes
-
Password generator
-
Token builder
-
String utilities
c) External API call builders
services.AddTransient<IRequestBuilder, RequestBuilder>();
d) Mappers
services.AddTransient<IObjectMapper, ObjectMapper>();
✔ When to use:
-
When service is very lightweight
-
When a fresh object is required every time
-
When the service is not shared and not dependent on state
π― Interview-Friendly Summary
Singleton → Use for caching, logging, config — shared for entire app
Scoped → Use for DbContext, repository, business logic — per request
Transient → Use for utility/helper classes — new instance every time
π₯ Quick 15-Second Answer
AddSingletonfor shared, long-lived services like cache or logging.
AddScopedfor per-request services like DbContext, repositories, and business services.
AddTransientfor lightweight, stateless utility services like mappers, formatters, token generators.
No comments:
Post a Comment