Open-Source .NET Programming • Intermediate • Estimated study time: 40 minutes
Applications become difficult to test when a component constructs every object it uses. Dependency injection (DI) separates object creation from object use. A monitoring service can receive an interface for reporting device status rather than constructing a particular console or database writer. The preceding configuration lesson established a related principle: operational choices can be separated from business logic.
Prerequisites and learning objectives
Use a supported .NET SDK, terminal and C# editor. Know classes, interfaces, constructors, generic methods and using declarations. By the end, learners will register a service and inject it through a constructor, predict object identity for transient, scoped and singleton registrations, create and dispose a scope, identify invalid lifetime combinations, and substitute a test implementation without changing the consumer.
From direct construction to constructor injection
A dependency is an object that another object needs to perform its work. An interface defines the operations available to a consumer. Constructor injection supplies an implementation through the constructor rather than embedding a construction decision in the consumer. Microsoft documents the built-in container in its dependency injection guide. Registration describes how to construct a service; resolution requests an instance from the service provider.
The following complete program shows constructor injection without an external container. Create a console project and replace Program.cs with the code:
IStatusWriter writer = new ConsoleStatusWriter();
var reporter = new RackReporter(writer);
reporter.Report(“rack-a”);
public interface IStatusWriter
{
void Write(string message);
}
public sealed class ConsoleStatusWriter : IStatusWriter
{
public void Write(string message)
=> Console.WriteLine(message);
}
public sealed class RackReporter
{
private readonly IStatusWriter _writer;
public RackReporter(IStatusWriter writer)
{
_writer = writer;
}
public void Report(string rack)
=> _writer.Write(rack + “: ready”);
}
Expected output:
rack-a: ready
RackReporter only knows the interface. A test can supply an implementation that records messages in memory rather than writing to the terminal. The constructor makes the dependency explicit and prevents the class from choosing an unrelated concrete writer internally.
Build a service lifetime laboratory
Install the dependency injection package in a separate console project. Review NuGet dependency security before restoring packages. Use the following terminal commands:
dotnet new console -n LifetimeLab
cd LifetimeLab
dotnet add package Microsoft.Extensions.DependencyInjection
A transient registration creates an instance for every resolution. A scoped registration reuses one instance within a particular scope; a different scope receives a different instance. A singleton registration reuses one instance across resolutions within the same root provider. The Microsoft service lifetime reference describes the boundaries. A web request commonly defines a scope, but a plain console program must establish its own scopes.
Replace Program.cs with the following complete example. ReferenceEquals checks object identity, not equality of object contents:
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddTransient<TransientProbe>();
services.AddScoped<ScopedProbe>();
services.AddSingleton<SingletonProbe>();
services.AddTransient<Reporter>();
using var provider = services.BuildServiceProvider(
new ServiceProviderOptions
{
ValidateScopes = true,
ValidateOnBuild = true
});
using var a = provider.CreateScope();
using var b = provider.CreateScope();
var a1 = a.ServiceProvider.GetRequiredService<Reporter>();
var a2 = a.ServiceProvider.GetRequiredService<Reporter>();
var b1 = b.ServiceProvider.GetRequiredService<Reporter>();
Console.WriteLine(ReferenceEquals(a1.Transient, a2.Transient));
Console.WriteLine(ReferenceEquals(a1.Scoped, a2.Scoped));
Console.WriteLine(ReferenceEquals(a1.Scoped, b1.Scoped));
Console.WriteLine(ReferenceEquals(a1.Singleton, b1.Singleton));
public sealed class TransientProbe { }
public sealed class ScopedProbe { }
public sealed class SingletonProbe { }
public sealed class Reporter
{
public Reporter(TransientProbe transient,
ScopedProbe scoped, SingletonProbe singleton)
{
Transient = transient;
Scoped = scoped;
Singleton = singleton;
}
public TransientProbe Transient { get; }
public ScopedProbe Scoped { get; }
public SingletonProbe Singleton { get; }
}
Execute the project with the following command:
dotnet run
Expected output:
False
True
False
True
Both reporters in scope a receive separate transient objects and the same scoped object. Scope b receives another scoped object. Both scopes share the singleton from their common root provider. The using declarations dispose the scopes before the provider, allowing the container to release its owned disposable services. Review SDK-style projects if the project does not build.
Avoid captive dependencies and resource leaks
A singleton must not directly hold a scoped service from a short-lived operation. Otherwise the shorter-lived object may be retained beyond its intended boundary. The validation settings in the lab help expose invalid registrations. Change Reporter from transient to singleton while leaving its ScopedProbe dependency scoped; the provider build should fail validation. A long-lived background worker should create and dispose a separate scope per operation using IServiceScopeFactory when it needs scoped services. See the Microsoft DI guidelines. Singleton services used concurrently must be thread-safe. A consumer normally must not dispose an object whose lifetime the container owns.
Exercises
1. Change TransientProbe to scoped and predict all four output lines. 2. Change ScopedProbe to singleton and predict the third line. 3. Register Reporter as singleton in the original example and explain the validation error. 4. Add an implementation of IStatusWriter that stores messages in a List<string> and inject it into RackReporter. 5. Explain why creating a fresh root provider for every operation is not equivalent to creating scopes.
Assessment and answer explanations
1. True, True, False, True; both reporters in scope a now receive the same formerly transient probe. 2. True, because both scopes resolve the same singleton. 3. A singleton cannot directly capture ScopedProbe, whose lifetime belongs to a narrower scope. 4. Implement Write by appending to a list; after calling Report, check that its sole item equals rack-a: ready. No changes to RackReporter are necessary. 5. Each root provider has its own singleton instances and disposal boundary. Creating scopes from one provider preserves shared singleton identity while isolating scoped objects.
Verification and troubleshooting
Run the original program before changing registrations. If the package cannot restore, inspect the package source, installed SDK and network policy. If scope validation fails, examine the full dependency chain rather than disabling validation. Compare each output line with its expected identity relationship. Revisit the common language runtime lesson for managed object behavior. The lab uses synthetic device identifiers and requires no production infrastructure.
We volunteer daily to ensure the credibility of the information on the platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiative, please scan the QR code below


Leave a Reply