Dependency injection lifetimes
Dependency injection lifetimes
Dependency injection (DI) means giving an object the collaborators it needs instead of making it construct them. A container creates and supplies registered services. Transient services are created on each resolution, scoped services are reused inside one scope, and singleton services are shared by resolutions of their registration in one container. Choose the lifetime according to ownership and state, not just allocation cost.
Proposed baseline: .NET SDK 10.0.404, net10.0 / C# 14. Requires installed ASP.NET Core 10 shared framework/reference pack (FrameworkReference Microsoft.AspNetCore.App); the examples are console programs, not web servers. C# results are reasoned, not executed. See the accompanying independent project fixture; approve dependencies and environment before restoring or building.
Inject a clock
An interface makes the clock replaceable. The fixed implementation makes a test independent of the current time.
using System;using Microsoft.Extensions.DependencyInjection;var services = new ServiceCollection();services.AddSingleton<IClock, FixedClock>();services.AddTransient<Report>();using var provider = services.BuildServiceProvider();Console.WriteLine(provider.GetRequiredService<Report>().Heading());public interface IClock { string Day { get; } }public sealed class FixedClock : IClock { public string Day => "Monday"; }public sealed class Report(IClock clock){ public string Heading() => $"Report: {clock.Day}";}The composition root registers the dependency and consumer. Report has no knowledge of the container. A different clock can be supplied without changing Report.
Expected observation (reasoned, not executed):
Report: MondayCompare three lifetimes
Use reference identity rather than random IDs to observe object reuse.
using System;using Microsoft.Extensions.DependencyInjection;var services = new ServiceCollection();services.AddSingleton<Shared>();services.AddScoped<Session>();services.AddTransient<Work>();using var root = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true });using var a = root.CreateScope();using var b = root.CreateScope();Console.WriteLine(ReferenceEquals(a.ServiceProvider.GetRequiredService<Shared>(), b.ServiceProvider.GetRequiredService<Shared>()));Console.WriteLine(ReferenceEquals(a.ServiceProvider.GetRequiredService<Session>(), a.ServiceProvider.GetRequiredService<Session>()));Console.WriteLine(ReferenceEquals(a.ServiceProvider.GetRequiredService<Session>(), b.ServiceProvider.GetRequiredService<Session>()));Console.WriteLine(ReferenceEquals(a.ServiceProvider.GetRequiredService<Work>(), a.ServiceProvider.GetRequiredService<Work>()));public sealed class Shared { }public sealed class Session { }public sealed class Work { }Singleton is shared across the two scopes, scoped is reused only in the same scope, and each transient resolution produces a new Work.
Expected observation (reasoned, not executed):
TrueTrueFalseFalseReject a captive scoped dependency
A singleton that stores a scoped service would keep it beyond the intended boundary. Enable scope validation explicitly.
using System;using Microsoft.Extensions.DependencyInjection;var services = new ServiceCollection();services.AddScoped<Session>();services.AddSingleton<Worker>();using var root = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true });try { _ = root.GetRequiredService<Worker>(); }catch (InvalidOperationException) { Console.WriteLine("Invalid lifetime"); }public sealed class Session { }public sealed class Worker(Session session){ public Session Current => session;}Resolve the scoped dependency inside a fresh scope for each background operation, typically via IServiceScopeFactory, instead of storing it in a singleton.
Expected observation (reasoned, not executed):
Invalid lifetimeCommon mistakes and edge cases
Container-created disposable services are disposed with their owning scope or root. An externally constructed singleton registered as an instance remains the caller’s disposal responsibility. A scope containing async-only disposable services needs asynchronous disposal, such as await using with CreateAsyncScope. Await the scoped work before the scope ends and do not return a scoped service to a longer-lived caller. Do not dispose injected services manually unless ownership was explicitly transferred. Resolving disposable transients from the root can retain them until shutdown. Singleton mutable state must be safe for concurrent callers. In ASP.NET Core a request normally has its own scope; a console app must create explicit scopes. Scope validation is useful but cannot prove thread safety. Register dependencies at the composition root; avoid passing IServiceProvider through business logic.
Practice and recap
Design a background worker that processes two independent jobs with a scoped unit of work and a shared immutable configuration. Explain how to dispose the scopes and predict whether the jobs share a unit of work.
Hint: Identify which state belongs to a job.
Learning objective: Choose singleton, scoped or transient based on ownership. See accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dependency injection lifetimes — knowledge check
Apply the lesson concepts to the following scenarios.
Why inject IClock into Report?
Two scoped resolutions in one scope return what?
What does a singleton capturing a scoped service risk?
Who disposes a container-created scoped disposable?
What must a mutable singleton consider?