Sobes.tech
Junior — Middle

How is the lifespan of an object determined after its registration in the dependency injection container?

sobes.tech AI

Answer from AI

The lifetime of an object in a dependency injection (DI) container is determined by its lifecycle, which is set during registration.

The main lifecycle options in C# (for example, in Microsoft.Extensions.DependencyInjection) are:

  • Transient: a new instance is created for each request.
  • Scoped: a single instance is created per scope (e.g., per HTTP request in a web application).
  • Singleton: a single instance is created on the first request and lives until the application terminates.

Example of registering a service with different lifetimes:

services.AddTransient<IMyService, MyService>(); // new object each time
services.AddScoped<IMyService, MyService>();   // one object per session/request
services.AddSingleton<IMyService, MyService>(); // one object for the entire lifetime

Thus, the lifetime of an object depends on the lifecycle chosen during registration in the DI container.