Transient creates a new instance on each resolution, scoped creates one per scope (normally one HTTP request), and singleton creates one for the application lifetime. Example: builder.Services.AddTransient<IReceiptFormatter, ReceiptFormatter>(); builder.Services.AddScoped<OrderService>(); builder.Services.AddDbContext<AppDbContext>(); builder.Services.AddSingleton<ISystemClock, SystemClock>(); A singleton must be thread-safe and must not capture a scoped DbContext. A background singleton that needs scoped services should create an IServiceScope per work item. Transient disposable services resolved from the root can remain retained until shutdown. Choose lifetime from ownership and state, and enable scope validation so invalid dependencies fail early.
Backbencher Developer · · 0 likes