03 Feb 2024
Intermediate
Examples for scoped , singleton and transient service lifetime in Asp.Net Core:
-
Singleton:
- Application Configuration: Singleton services are often used to store and provide access to application-wide configuration settings that remain constant throughout the lifetime of the application.
services.AddSingleton<IConfiguration>(Configuration);
- Logging Service: A logging service implemented as a singleton allows all components of the application to log events and errors to a shared logging infrastructure.
services.AddSingleton<ILoggerManager, LoggerManager>();
- Application-wide Event Bus or Message Broker: Singleton services can be used to implement event buses or message brokers that facilitate communication between different parts of the application.
services.AddSingleton<IEventBus, EventBus>();
- Repository Cache: A repository cache that stores frequently accessed data in memory can be implemented as a singleton to ensure that the cached data is shared across all parts of the application.
services.AddSingleton<IRepositoryCache, RepositoryCache>();
- Stateless Calculation Service: Services that perform stateless calculations or computations, such as mathematical operations or data transformations, can be implemented as singletons to promote code reuse and efficiency.
services.AddSingleton<ICalculationService, CalculationService>();
- Application Configuration: Singleton services are often used to store and provide access to application-wide configuration settings that remain constant throughout the lifetime of the application.
-
Scoped:
- Database Context: In a web application, a scoped database context ensures that each HTTP request gets its own instance of the database context. This helps maintain data integrity and prevents data leakage between different requests.
services.AddScoped<MyDbContext>();
- Unit of Work Pattern: Scoped services are often used in conjunction with the unit of work pattern, where a scoped service manages a set of operations within a single HTTP request, such as database transactions or other related tasks.
services.AddScoped<IUnitOfWork, UnitOfWork>();
- Caching Service with Per-Request Cache: A caching service scoped to the HTTP request can cache data specific to that request, optimizing performance for subsequent operations within the same request.
services.AddScoped<ISessionManager, SessionManager>();
- Session Management Service: Services responsible for managing user sessions in a web application can be scoped to ensure that session data is isolated and managed within the context of each individual HTTP request.
- User Context Service: Services that provide contextual information about the current user, such as authentication and authorization details, can be scoped to the current HTTP request to ensure that the information remains consistent throughout the request lifecycle.
services.AddScoped<IUserContext, UserContext>();
- Database Context: In a web application, a scoped database context ensures that each HTTP request gets its own instance of the database context. This helps maintain data integrity and prevents data leakage between different requests.
-
Transient:
- Repository Classes for Short-lived Operations: Transient services are commonly used for repository classes that perform short-lived database operations, such as querying or updating data in response to a specific user action.
services.AddTransient<IRepository<User>, UserRepository>();
- Request-specific Validators: Validators used to validate input data for a specific HTTP request can be implemented as transient services to ensure that each request gets its own instance of the validator with its own state.
services.AddTransient<IValidator, RequestValidator>();
- Temporary Data Transformers: Services responsible for transforming data received from external sources into a format suitable for processing within a specific request can be implemented as transient services to avoid sharing state between different requests.
services.AddTransient<IDataTransformer, TemporaryDataTransformer>();
- Disposable Resources: Services that wrap disposable resources, such as file streams or network connections, can be implemented as transient services to ensure that the resources are properly disposed of after use.
services.AddTransient<IDisposableResourceService, DisposableResourceService>();
- Transient Worker or Background Task Services: Services responsible for executing short-lived background tasks or worker processes can be implemented as transient services to ensure that each task is executed in its own isolated environment.
services.AddTransient<IBackgroundTaskService, TransientBackgroundTaskService>();
- Repository Classes for Short-lived Operations: Transient services are commonly used for repository classes that perform short-lived database operations, such as querying or updating data in response to a specific user action.