Junior — Middle
How do the lifecycles of objects differ in Dependency Injection for transient, scoped, and singleton modes?
sobes.tech AI
Answer from AI
In Dependency Injection (DI) in C#, the lifecycle of an object is determined by its registration mode:
-
Transient: a new instance is created each time the object is requested. Used for lightweight, stateless services.
-
Scoped: the object is created once per scope, typically per HTTP request in web applications. All dependencies within this request share the same instance.
-
Singleton: the object is created once upon the first request and lives for the duration of the application. All requests share the same instance.
Example registration in ASP.NET Core:
services.AddTransient<IService, Service>(); // new object each time
services.AddScoped<IService, Service>(); // one object per request
services.AddSingleton<IService, Service>(); // one object for the entire lifetime
Thus, the choice of mode depends on how long the object should live and how it is used.