liveBook · Manning

Service lifetime

As explained in Pro ASP.NET Core 7, Tenth Edition

A service lifetime is the dependency-injection rule governing when service instances are created and how long they are retained.

A service lifetime is the dependency-injection rule that controls when a service instance is created and how long it is retained. ASP.NET Core services support shared application functionality such as logging and database access; registration in Program.cs determines how dependencies are resolved. section 14.0

Choose the registration according to the required instance boundary:

  • Transient: AddTransient creates a new implementation instance for every dependency resolution. A GuidService with a private Guid makes repeated resolutions visibly different. section 14.4.1
  • Scoped: AddScoped provides the usual one-service-object-per-HTTP-request behavior. Resolve it through HttpContext.RequestServices so the service belongs to the current request scope. section 14.4.3
  • Dependencies can use different lifetimes, but a dependency resolved through a scoped service can behave as though it has the scoped lifetime. section 14.5.1

Observe the lifetime

Register `builder.Services.AddTransient<IResponseFormatter, GuidService>()`, inject `IResponseFormatter` into the `endpoint/function` handler, and request `/endpoint/function`. Different GUID values demonstrate transient resolution. Change the registration to `AddScoped`; resolutions within one HTTP request then use the scoped service object.

When configuring the request pipeline in Program.cs, create a scope before obtaining a scoped service; requesting one without a scope raises an exception. Dependency chains are resolved by inspecting constructors and recursively creating required services. section 14.4.3 section 14.5.1

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains transient and scoped resolution, request scopes, endpoint instantiation, manual scopes, and mixed-lifetime effects.
Examples
Demonstrates GuidService, endpoint handlers, middleware parameters, request-scoped resolution, and timestamping through a chained service.
What it assumes
Assumes basic ASP.NET Core application structure while introducing service registration, resolution, and dependency-injection behavior.
What you can do after
Apply it via AddTransient, AddScoped, RequestServices, and CreateScope, then verify behavior through endpoint responses.
How it connects
Connects dependency injection with service providers, HTTP requests, middleware, endpoints, constructor injection, and dependency chains.

Also explained in

Compare how 2 books explain service lifetime →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.