liveBook · Manning

Transient lifetime

As explained in ASP.NET Core in Action, 3e

A transient lifetime is a dependency-injection lifetime policy that creates a new service instance each time the service is requested.

A transient lifetime tells the ASP.NET Core dependency-injection container to create a new service instance every time that service is requested. Different parts of one dependency graph can therefore receive different instances of the same type. section 9.4 section 9.4.1

Use transient registration with these practical expectations:

  • Register a service with AddTransient<T>() or AddTransient<TService, TImplementation>(). section 9.4.1 section 9.1
  • Expect new instances both between HTTP requests and within a single request. section 9.4.1
  • Prefer lightweight services with little or no state, because transient registration can create many objects. section 9.4.1
  • Resolve transient services from an active scope; create and dispose a scope when resolving them outside an HTTP request. section 9.5 section 9.6

Seeing unique instances

Register both DataContext and Repository as transient. A handler receives DataContext directly while Repository receives its own DataContext dependency. Reading RowCount from both can produce different values in the same request, demonstrating that each request creates a fresh instance. section 9.4.1 section 9.4

builder.Services.AddTransient<DataContext>();
builder.Services.AddTransient<Repository>();

Inspect the minimal AddTransient registration for DataContext and Repository. section 9.4.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains instance creation within dependency graphs, object volume, manual scopes, and lifetime safety, but stops short of container internals.
Examples
Demonstrates unique DataContext and Repository instances through AddTransient registrations, RowCount values, an endpoint handler, and repeated API calls.
What it assumes
Assumes dependency-injection registration basics while defining service lifetimes and showing how dependencies are supplied.
What you can do after
Operate/configure it through ASP.NET Core AddTransient registrations and diagnose incorrect root-container resolution or lifetime capture.
How it connects
Connects transient lifetime to dependency injection, dependency graphs, scoped lifetime, singleton lifetime, and captive dependencies.

Also explained in

Compare how 2 books explain transient lifetime →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.