An online shop's OrderService accepts orders and emails the customer. For the email it creates the mail server itself with new SmtpEmailSender(), and it takes the time from DateTime.Now. Now try to test it: every test would send a real email, and the result would depend on the clock. If tomorrow you want SMS instead of email, you will have to change OrderService. The reason is always the same: the class creates its own dependencies and is glued to them. Dependency injection (DI) undoes that glue. You saw it in the lesson «A Web API with ASP.NET Core» with AddDbContext and met fake objects with Moq in «Testing with xUnit»; now let's look inside the mechanism.
Why DI: from `new` to the constructor
Dependency and dependency injectionDefinition
A dependency is another object a class needs in order to work (an email sender, a clock, a database). Injection means the class does not create these objects itself but receives them from outside, usually as constructor parameters.
Tight coupling: the class creates its dependencies
class OrderService
{
private readonly SmtpEmailSender _email = new();
public void PlaceOrder(string customer, string product)
{
string time = DateTime.Now.ToString("HH:mm");
_email.Send(customer, $"{product} ordered at {time}");
}
}Constructor injection: dependencies arrive as interfaces
class OrderService(IEmailSender email, IClock clock)
{
public void PlaceOrder(string customer, string product)
{
string time = clock.Now.ToString("HH:mm");
email.Send(customer, $"{product} ordered at {time}");
}
}IEmailSender, IClock)You know interfaces from the lesson «Inheritance, interfaces and polymorphism»: an interface says “what” must be done and hides “how”. Below, the objects are created by hand at the top of Program.cs and passed to each other. This single place where the objects are assembled is called the composition root.
var clock = new FixedClock(new DateTime(2026, 10, 3, 9, 30, 0));
var service = new OrderService(new ConsoleEmailSender(), clock);
service.PlaceOrder("Aysel", "Physics textbook");
interface IEmailSender { void Send(string to, string text); }
interface IClock { DateTime Now { get; } }
class ConsoleEmailSender : IEmailSender
{
public void Send(string to, string text) => Console.WriteLine($"To {to}: {text}");
}
class SystemClock : IClock { public DateTime Now => DateTime.Now; }
class FixedClock(DateTime now) : IClock { public DateTime Now => now; }
class OrderService(IEmailSender email, IClock clock)
{
public void PlaceOrder(string customer, string product)
{
string time = clock.Now.ToString("HH:mm");
email.Send(customer, $"{product} ordered at {time}");
}
}Expected output
To Aysel: Physics textbook ordered at 09:30
OrderService is created with a fixed clock and a console “mailer”SystemClock is for the real program, while FixedClock always returns 09:30, so the result is repeatable. We changed the dependencies without touching a single letter of OrderService. DI gives four benefits: implementations are easy to swap, tests can use fakes, every class does one job, and dependencies are visible in the constructor — there are no hidden news.
The container: ServiceCollection
In an app with fifty classes, assembling objects by hand is long and tiring. A DI container does this work: you write rules such as “when IEmailSender is requested, give a ConsoleEmailSender”, and it looks at the constructors and creates the needed objects recursively. The .NET built-in container lives in the Microsoft.Extensions.DependencyInjection package (dotnet add package Microsoft.Extensions.DependencyInjection); ASP.NET Core and the generic host already include it.
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddSingleton<IClock>(new FixedClock(new DateTime(2026, 10, 3, 9, 30, 0)));
services.AddTransient<IEmailSender, ConsoleEmailSender>();
services.AddTransient<OrderService>();
using ServiceProvider provider = services.BuildServiceProvider();
var orders = provider.GetRequiredService<OrderService>();
orders.PlaceOrder("Murad", "Chess set");
var broken = new ServiceCollection();
broken.AddTransient<OrderService>();
broken.AddSingleton<IClock, SystemClock>();
try
{
broken.BuildServiceProvider().GetRequiredService<OrderService>();
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
}Expected output
To Murad: Chess set ordered at 09:30 Unable to resolve service for type 'IEmailSender' while attempting to activate 'OrderService'.
AddSingleton<IClock>(new FixedClock(...)) registers a ready-made object. AddTransient<IEmailSender, ConsoleEmailSender>() maps the interface to a class, and AddTransient<OrderService>() registers a concrete class as itself. When GetRequiredService<OrderService>() is called, the container sees IEmailSender and IClock in the constructor, finds them and passes them in. In the second part IEmailSender was forgotten: the error is thrown not when the provider is built but when OrderService is requested, and it says exactly what is missing.
Lifetimes: singleton, scoped, transient
| Lifetime | When it is created | Typical use |
|---|---|---|
AddSingleton | once for the whole app | settings, a cache, a clock |
AddScoped | once per scope; in ASP.NET Core a scope is one HTTP request | DbContext, a cart, per-request state |
AddTransient | a new one on every request | lightweight stateless helpers |
To see the difference, every class counts its own instances. In a console app we create the scope ourselves with CreateScope() and use it as two “requests”:
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddSingleton<SingletonService>();
services.AddScoped<ScopedService>();
services.AddTransient<TransientService>();
using ServiceProvider provider = services.BuildServiceProvider();
for (int request = 1; request <= 2; request++)
{
using IServiceScope scope = provider.CreateScope();
IServiceProvider sp = scope.ServiceProvider;
int s = sp.GetRequiredService<SingletonService>().Id;
int c1 = sp.GetRequiredService<ScopedService>().Id, c2 = sp.GetRequiredService<ScopedService>().Id;
int t1 = sp.GetRequiredService<TransientService>().Id, t2 = sp.GetRequiredService<TransientService>().Id;
Console.WriteLine($"Request {request}: singleton {s}, scoped {c1}/{c2}, transient {t1}/{t2}");
}
class SingletonService { static int count; public int Id { get; } = ++count; }
class TransientService { static int count; public int Id { get; } = ++count; }
class ScopedService : IDisposable
{
static int count;
public int Id { get; } = ++count;
public void Dispose() => Console.WriteLine($" scoped {Id} disposed");
}Expected output
Request 1: singleton 1, scoped 1/1, transient 1/2 scoped 1 disposed Request 2: singleton 1, scoped 2/2, transient 3/4 scoped 2 disposed
The singleton is number 1 in both requests — one instance for the whole app. The scoped service is the same within a request (1/1) and new in the next one (2/2). The transient service is new every time: 1/2, then 3/4. When a scope is closed, the container itself calls Dispose on the IDisposable services it created there — the line scoped 1 disposed shows it. Singletons are disposed when the provider itself is disposed.
Captive dependencyDefinition
A long-lived service (for example a singleton) holding on to a service that should live for a shorter time (scoped or transient). The short-lived service is “captured” and lives much longer than intended.
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddScoped<ShoppingCart>();
services.AddSingleton<CheckoutService>();
using ServiceProvider provider = services.BuildServiceProvider();
foreach (string user in new[] { "Aysel", "Murad" })
{
using IServiceScope scope = provider.CreateScope();
var checkout = scope.ServiceProvider.GetRequiredService<CheckoutService>();
checkout.Add($"{user}'s book");
Console.WriteLine($"{user} sees: {checkout.Items}");
}
try
{
services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true });
}
catch (AggregateException ex)
{
Console.WriteLine(ex.InnerException?.Message);
}
class ShoppingCart { public List<string> Items { get; } = []; }
class CheckoutService(ShoppingCart cart)
{
public void Add(string item) => cart.Items.Add(item);
public string Items => string.Join(", ", cart.Items);
}Expected output
Aysel sees: Aysel's book Murad sees: Aysel's book, Murad's book Error while validating the service descriptor 'ServiceType: CheckoutService Lifetime: Singleton ImplementationType: CheckoutService': Cannot consume scoped service 'ShoppingCart' from singleton 'CheckoutService'.
CheckoutService is a singleton and is created once, on the first request; it keeps the ShoppingCart it received then forever. Murad sees Aysel's book in his cart: in a web app this means users' data getting mixed up. The rule: a service may depend only on services that live as long as it does or longer. ValidateScopes and ValidateOnBuild catch this mistake when the app starts; ASP.NET Core and the generic host switch them on themselves in the Development environment.
The generic host in a console app and keyed services
Host.CreateApplicationBuilder (the Microsoft.Extensions.Hosting package) gives a console app the same ready-made infrastructure as ASP.NET Core: the DI container, configuration (appsettings.json, environment variables, the command line), logging and information about the environment. The example below also shows several implementations of one interface and the keyed services that arrived in .NET 8.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services.AddSingleton<INotifier, EmailNotifier>();
builder.Services.AddSingleton<INotifier, SmsNotifier>();
builder.Services.AddKeyedSingleton<INotifier, SmsNotifier>("urgent");
builder.Services.AddTransient<AlertService>();
using IHost host = builder.Build();
var alerts = host.Services.GetRequiredService<AlertService>();
alerts.Broadcast("Lesson moved to room 204");
alerts.Urgent("Fire drill at 11:00");
Console.WriteLine(host.Services.GetRequiredService<INotifier>().GetType().Name);
Console.WriteLine(host.Services.GetRequiredService<IHostEnvironment>().EnvironmentName);
interface INotifier { void Send(string message); }
class EmailNotifier : INotifier { public void Send(string m) => Console.WriteLine($"Email: {m}"); }
class SmsNotifier : INotifier { public void Send(string m) => Console.WriteLine($"SMS: {m}"); }
class AlertService(IEnumerable<INotifier> all, [FromKeyedServices("urgent")] INotifier urgent)
{
public void Broadcast(string message)
{
foreach (INotifier notifier in all) notifier.Send(message);
}
public void Urgent(string message) => urgent.Send($"URGENT {message}");
}Expected output
Email: Lesson moved to room 204 SMS: Lesson moved to room 204 SMS: URGENT Fire drill at 11:00 SmsNotifier Production
The IEnumerable<INotifier> parameter receives all implementations registered without a key, in registration order — email and SMS. When a single INotifier is requested, the last registration wins: SmsNotifier. AddKeyedSingleton<INotifier, SmsNotifier>("urgent") registers a service with a key, and [FromKeyedServices("urgent")] picks exactly that one in a constructor; keyed registrations do not appear in the ordinary list. The host registered IHostEnvironment itself: if the DOTNET_ENVIRONMENT variable is not set, the environment is Production. Long-running background work uses AddHostedService<T>() and await host.RunAsync() — then the app runs until Ctrl+C.
Testing with fakes
The real gift of DI is in tests. A test needs no container: you create the object by hand with fake dependencies. A fake is a small hand-written implementation of an interface: FakeEmailSender does not send letters but writes them to a list, and FixedClock always returns the same time. Moq from the lesson «Testing with xUnit» generates such objects automatically, but in simple cases a hand-written fake is clearer.
public class FakeEmailSender : IEmailSender
{
public List<(string To, string Text)> Sent { get; } = [];
public void Send(string to, string text) => Sent.Add((to, text));
}
public class OrderServiceTests
{
[Fact]
public void PlaceOrder_SendsOneEmailWithTheTime()
{
var email = new FakeEmailSender();
var clock = new FixedClock(new DateTime(2026, 10, 3, 9, 30, 0));
var service = new OrderService(email, clock);
service.PlaceOrder("Aysel", "Physics textbook");
var sent = Assert.Single(email.Sent);
Assert.Equal("Aysel", sent.To);
Assert.Equal("Physics textbook ordered at 09:30", sent.Text);
}
}Expected output
Passed! - Failed: 0, Passed: 1, Skipped: 0, Total: 1, Duration: 18 ms - Shop.Tests.dll (net10.0)
Shop.Tests project (dotnet new xunit); the output of dotnet testThe test runs in a few milliseconds without an SMTP server or waiting for 09:30, and gives the same result every time. Assert.Single checks that exactly one email was sent and returns it; then the recipient and the text are checked. The code of OrderService is exactly the same as in the real program — the test checks its behaviour, not the outside world.
Summary and practice
- A class does not create its dependencies but receives them as interfaces in its constructor; objects are assembled in one place, the composition root.
ServiceCollectionstores the rules,BuildServiceProviderbuilds the container, andGetRequiredServicecreates the object graph.- Singleton — once, scoped — once per scope, transient — new every time; a long-lived service must not hold a short-lived one.
- The generic host gives a console app DI, configuration and logging; tests use fakes instead of the container.
Task 1: how many instances are created?
Problem
A is registered as a singleton, B as scoped and C as transient. The program creates two scopes and requests A, B and C twice in each scope. How many instances of each class are created in total?
Show solutionHide solution
Solution
A.2) Scoped means one per scope, and repeated requests inside a scope get the same object: 2 instances of
B.3) Transient is new on every request: 2 scopes × 2 requests = 4 instances of
C.This matches the lifetimes example:
singleton 1, scoped 1/1 and 2/2, transient 1/2 and 3/4.Task 2: a greeting that depends on the clock
Problem
GreetingService receives an IClock: before 12 o'clock it returns Good morning, {name}!, afterwards Good afternoon, {name}!. Write an xUnit test that checks both cases without changing the system clock.
Show solutionHide solution
Solution
public class GreetingService(IClock clock) and public string Greet(string name) => clock.Now.Hour < 12 ? $"Good morning, {name}!" : $"Good afternoon, {name}!";2) A
[Theory] checks both cases: [InlineData(9, "Good morning, Leyla!")] and [InlineData(15, "Good afternoon, Leyla!")].3) In the test method:
var clock = new FixedClock(new DateTime(2026, 10, 3, hour, 0, 0));, var service = new GreetingService(clock);, Assert.Equal(expected, service.Greet("Leyla"));.4)
dotnet test reports the two new test cases as passed. Without the fake clock, the test could pass only at certain hours of the day.Remember
- DI: a class does not create its dependencies with
newbut receives them as interfaces in its constructor, removing tight coupling. ServiceCollection+BuildServiceProvider+GetRequiredService; a missing registration gives anInvalidOperationExceptionwhen the object is requested.- A singleton is one for the app, scoped is one per scope (HTTP request), transient is new every time; when a scope closes, the container calls
Dispose. - A captive dependency is a singleton holding a scoped service;
ValidateScopesandValidateOnBuildcatch it at startup. - Several registrations of one interface:
IEnumerable<T>gives all of them, a singleTthe last one; keyed services are chosen with[FromKeyedServices]. - Tests need no container: create the object by hand with fake dependencies (
FakeEmailSender,FixedClock).