ASP.NET Core Interview Question #56

When should you use a Transient service?

Dependency Injection & Services Junior Beginner

Quick Interview Answer

Use a Transient lifetime when a service is lightweight, stateless, inexpensive to construct, and should not retain state between resolutions.

Detailed Explanation

Use a Transient lifetime when a service is lightweight, stateless, inexpensive to construct, and should not retain state between resolutions.

Examples can include formatting helpers, validators, mappers, or small calculation services. A new instance is produced each time the service is requested, even multiple times within the same HTTP request.

Transient does not automatically mean better isolation. If construction is expensive or the service owns costly resources, another lifetime or an appropriate factory/pooling strategy may be more suitable.

Code Example

builder.Services.AddTransient<IPriceCalculator, PriceCalculator>();

public class PriceCalculator : IPriceCalculator
{
    public decimal ApplyTax(decimal amount, decimal rate)
        => amount + (amount * rate);
}