Junior — Middle
How is the lifespan of an object determined after it is injected via Dependency Injection?
sobes.tech AI
Answer from AI
The lifetime of an object created through Dependency Injection (DI) is determined by the lifetime (lifetime), which is set during the service registration in the DI container. In C# (for example, in ASP.NET Core), there are three main types of lifetime:
- Transient — a new instance is created for each service request.
- Scoped — a single instance is created per scope (e.g., per HTTP request) and reused within that scope.
- Singleton — a single instance is created on the first request and lives until the application terminates.
Example registration:
services.AddTransient<IMyService, MyService>();
services.AddScoped<IMyService, MyService>();
services.AddSingleton<IMyService, MyService>();
Thus, the lifetime of an object depends on the chosen lifetime during registration in the DI container.