What types of object lifecycle exist in an IoC container, and how are they applied?
sobes.tech AI
Answer from AI
In IoC (Inversion of Control) containers, the following object lifecycle types are commonly used:
-
Transient — the container creates a new instance of the object each time it is requested. Used when a new object is needed for each operation.
-
Singleton — the container creates one instance of the object on the first request and returns it for all subsequent requests. Suitable for services with state or resources that should be unique.
-
Scoped — the object is created once per scope (e.g., per request in a web application) and reused within that scope. After the scope ends, the object is destroyed.
Example in C# using Microsoft.Extensions.DependencyInjection:
services.AddTransient<IService, Service>(); // new object each time
services.AddSingleton<IService, Service>(); // one object for the entire application lifetime
services.AddScoped<IService, Service>(); // one object per HTTP request
The choice of lifecycle depends on the object’s state requirements and application performance.