Choose .NET dependency injection lifetimes and validate scopes
A service lifetime determines when the container creates an instance and how long it owns that instance. Choose it according to state, concurrency and disposal requirements. The built-in .NET container offers transient, scoped and singleton registrations.
Transient services are created for each resolution. Scoped services are reused within one scope. Singleton services are reused for the lifetime of their owning root provider. An ASP.NET Core request normally has a scope, but a standalone console application must create scopes explicitly when it needs them.
Observe identity and disposal
Create a .NET 10 console application with dotnet new console -n LifetimeDemo -f net10.0. Inside that directory run dotnet add package Microsoft.Extensions.DependencyInjection --version 10.0.*. Replace Program.cs and run dotnet run.
using System;
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddTransient<TransientStamp>();
services.AddScoped<ScopedStamp>();
services.AddSingleton<SingletonStamp>();
using var provider = services.BuildServiceProvider(new ServiceProviderOptions {
ValidateScopes = true,
ValidateOnBuild = true
});
ScopedStamp firstScoped;
SingletonStamp firstSingleton;
using (var first = provider.CreateScope()) {
var scopedProvider = first.ServiceProvider;
firstScoped = scopedProvider.GetRequiredService<ScopedStamp>();
firstSingleton = scopedProvider.GetRequiredService<SingletonStamp>();
Console.WriteLine($"Transient same={ReferenceEquals(scopedProvider.GetRequiredService<TransientStamp>(), scopedProvider.GetRequiredService<TransientStamp>())}");
Console.WriteLine($"Scoped same={ReferenceEquals(firstScoped, scopedProvider.GetRequiredService<ScopedStamp>())}");
}
Console.WriteLine($"First scope disposed={firstScoped.IsDisposed}");
using (var second = provider.CreateScope()) {
Console.WriteLine($"Scoped across scopes={ReferenceEquals(firstScoped, second.ServiceProvider.GetRequiredService<ScopedStamp>())}");
Console.WriteLine($"Singleton across scopes={ReferenceEquals(firstSingleton, second.ServiceProvider.GetRequiredService<SingletonStamp>())}");
}
var invalid = new ServiceCollection();
invalid.AddScoped<ScopedStamp>();
invalid.AddSingleton<CapturedScope>();
try {
using var rejected = invalid.BuildServiceProvider(new ServiceProviderOptions {
ValidateScopes = true,
ValidateOnBuild = true
});
} catch (AggregateException) {
Console.WriteLine("Rejected singleton capturing scoped service");
}
sealed class TransientStamp { }
sealed class SingletonStamp { }
sealed class ScopedStamp : IDisposable {
public bool IsDisposed { get; private set; }
public void Dispose() => IsDisposed = true;
}
sealed class CapturedScope {
public CapturedScope(ScopedStamp value) => Value = value;
public ScopedStamp Value { get; }
}
Expected output:
Transient same=False
Scoped same=True
First scope disposed=True
Scoped across scopes=False
Singleton across scopes=True
Rejected singleton capturing scoped service
The retained firstScoped reference exists only to inspect the disposal flag. Application code must not continue using a service after its scope has ended.
Match ownership to the work
Use a scoped lifetime for a unit of work that should share state and be released together. A database context is a common example. A singleton must support concurrent access if its consumers can call it concurrently. Registration as a singleton does not automatically make mutable state thread-safe.
A transient injected into a singleton is resolved when the singleton is created and retained by that singleton. “Transient” does not mean that a fresh instance appears on every method call. Disposable transients resolved from a container are also tracked for disposal. Repeatedly resolving them from the root can retain them until shutdown.
Reject a captured scope
The invalid registration models a singleton that holds a scoped service. That longer-lived object would keep using state beyond its intended unit of work. ValidateScopes detects the relationship, while ValidateOnBuild checks constructible registrations when the provider is built. Validation is useful evidence, not a proof of all runtime behavior, especially for dependencies created inside factories.
A background service that processes separate jobs can inject IServiceScopeFactory, create a scope per job, resolve the job's services there and dispose the scope after completion. Keep the entire asynchronous operation inside that scope. Use an asynchronous scope when the owned services require asynchronous disposal.
Let the application host build its provider once. This standalone example builds providers to make the lifetime experiment observable. Building extra providers during registration creates extra singleton instances and separate disposal ownership, which defeats the intended application lifetime.
References



Question provenance
This article addresses AddTransient, AddScoped and AddSingleton Services Differences , asked by Elvin Mammadov on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored for current .NET. No answer text or code is reproduced.
Author: Herman Schoenfeld