A transient lifetime means the dependency injection container creates a new instance every time the service is requested. If two classes in the same HTTP request both depend on it, each receives its own instance. Even resolving it twice in one class gives two instances. Registration builder.Services.AddTransient<IEmailTemplateRenderer, EmailTemplateRenderer>(); Where it is used 1. Lightweight, stateless services - Formatters, mappers, validators, calculators, template renderers, small helper services. Creating them is cheap, and a fresh instance avoids any accidental sharing of state. 2. Services with short-lived mutable state - A builder object or a class that accumulates data for one operation, which must not be shared between consumers. 3. Typed HttpClients - AddHttpClient<TClient>() registers the typed client as transient; IHttpClientFactory pools and reuses the underlying HTTP handlers, so creating client instances frequently is cheap and avoids socket exhaustion. 4. FluentValidation validators and some middleware-related helpers are commonly registered as transient (or scoped). Example public sealed class SlugGenerator : ISlugGenerator { public string Create(string title) => Regex.Replace(title.ToLowerInvariant(), "[^a-z0-9]+", "-").Trim('-'); } builder.Services.AddTransient<ISlugGenerator, SlugGenerator>(); Considerations - Performance: many transient allocations of heavy objects increase GC pressure. For expensive, thread-safe, stateless services, a singleton may be better. - Disposal: transient services implementing IDisposable are tracked by the scope that created them and disposed when the scope ends. Resolving transient disposables from the root provider (outside a scope) keeps them alive until the application shuts down — a memory leak risk. - Captured transients: if a singleton depends on a transient service, that transient instance lives as long as the singleton. Make sure such services are thread-safe, or avoid the dependency. - Transient services can safely depend on scoped or singleton services, as long as they are resolved within a scope. Comparison in one line: transient is new every time, scoped is one per request, singleton is one for the whole application.
Ravindra Wadile · · 0 likes