Sobes.tech
Junior — Middle

Can you name other object lifecycle types used in IoC containers besides singleton?

sobes.tech AI

Answer from AI

In addition to the Singleton lifecycle, IoC containers often use the following object lifecycle types:

  • Transient: each request for an object creates a new instance. Used when a fresh object without preserved state is needed.
  • Scoped: the object is created once per scope, for example, per HTTP request in web applications. After the scope ends, the object is destroyed.
  • Per Thread: the object is created once per thread, useful for multi-threaded applications.

Example in C# using Microsoft.Extensions.DependencyInjection:

services.AddSingleton<IMyService, MyService>(); // Singleton
services.AddTransient<IMyService, MyService>(); // Transient
services.AddScoped<IMyService, MyService>();   // Scoped