Middle
Dependency Injection — how does it work? What are the differences in service lifetimes?
sobes.tech AI
Answer from AI
Dependency Injection (DI) is a pattern that allows dependencies of an object to be passed from outside rather than created internally. In C#, DI is often implemented through constructors, properties, or methods, and is also supported by frameworks such as Microsoft.Extensions.DependencyInjection.
An important part of DI is managing the lifetime of services:
- Transient — the service is created each time it is requested. Used for lightweight, stateless objects.
- Scoped — the service is created once per scope (e.g., per HTTP request in a web application). Allows maintaining state within a single request.
- Singleton — the service is created once for the entire lifetime of the application and reused.
Example of service registration:
services.AddTransient<IService, Service>();
services.AddScoped<IService, Service>();
services.AddSingleton<IService, Service>();
Thus, DI simplifies testing, enhances modularity and manageability of code, and the lifetime settings of services help control resources and object state.