Shows testing with DI: constructor-injected unit tests without a container, WebApplicationFactory with ConfigureTestServices to replace services, RemoveAll and Replace, fakes vs mocks, FakeTimeProvider, and testing the composition root with ValidateOnBuild.
Good DI makes unit tests container-free: if a class takes its dependencies through the constructor, the test just calls new OrderService(fakeRepo, fakeClock).
For integration tests, WebApplicationFactory<Program> boots the real app and container in memory. In ConfigureTestServices, which runs after Program.cs registrations, you swap external boundaries: services.RemoveAll<IPaymentGateway>(); services.AddSingleton<IPaymentGateway, FakePaymentGateway>();.
Prefer fakes (in-memory implementations, FakeTimeProvider) for state, and mocks only to verify interactions at boundaries.
The trade-off: replacing too much tests your mocks instead of your app; replace only what crosses a process boundary.
"I think about it at two levels. For unit tests, DI's job is to make the container unnecessary. If
OrderServicetakesIOrderRepositoryandTimeProviderin its constructor, my test constructs it directly with an in-memory repository andFakeTimeProvider. If I find myself building aServiceCollectionin a unit test, it usually means the class has hidden dependencies or does too much.For integration tests I want the real composition root, because that's where registration bugs live.
WebApplicationFactory<Program>runsProgram.csin memory with aTestServer. I override withWithWebHostBuilder(b => b.ConfigureTestServices(services => ...)).ConfigureTestServicesruns after the app's own registrations, so a plainAddwould already win for single resolution, but I still doRemoveAll<T>()thenAddso it's explicit and soIEnumerable<T>consumers don't see both. I replace only things that leave the process: the payment gateway, the email sender, the clock, external HTTP APIs. The database I'd rather run for real in a Testcontainers SQL Server than swap for the EF in-memory provider, which behaves differently.On fakes versus mocks: fakes are working lightweight implementations, like an in-memory email outbox I can assert against. Mocks verify that a call happened with certain arguments. I use mocks sparingly, at boundaries, because heavy mocking couples tests to implementation details. The mistake I see is integration tests that mock half the app's own services, which then pass while production is broken."
| Test type | Container? | How dependencies are supplied |
|---|---|---|
| Unit test | No | new Sut(fake1, fake2) |
| Composition-root test | Yes, the real one | Build host with ValidateOnBuild + ValidateScopes, resolve key services |
| Integration test | Yes, the real one | WebApplicationFactory + ConfigureTestServices swaps boundaries |
| End-to-end test | Deployed app | No swapping; test environment configuration |
| Double | What it is | Use for |
|---|---|---|
| Fake | Working simplified implementation (in-memory repo, FakeTimeProvider) |
State-based assertions; most cases |
| Stub | Returns canned answers | Driving a branch |
| Mock | Records and verifies calls | Asserting an interaction at a boundary ("sent exactly one email") |
A team's integration tests mocked the repository and the domain service, so they passed while a missing registration for a new validator crashed the endpoint in staging. Switching to the real composition root with only email and payments faked, plus a ValidateOnBuild test, caught the next two missing registrations in CI. The suite went from 40 seconds to 70 seconds, a cost the team accepted.
Checks the candidate uses DI to make tests simple and realistic, not to mock everything.
Green flags
ConfigureTestServices runs after app registrations and uses RemoveAllRed flags
Test ──▶ WebApplicationFactory<Program>
│ runs Program.cs (top-level statements) via a host factory hook
│ builder.Services.Add... ← app registrations
│ ConfigureTestServices(...) ← test overrides, run after
▼
TestServer (in-memory, no sockets)
│
HttpClient from factory.CreateClient()
Because ConfigureTestServices callbacks run after the app's ConfigureServices, your registrations come last. With top-level statements you expose Program to the test project using public partial class Program; or InternalsVisibleTo.
services.RemoveAll<T>() + services.AddX<T, Fake>(): explicit, clears multi-registrations.services.Replace(ServiceDescriptor.Singleton<T, Fake>()): removes only the first registration.HttpClients, replace the primary handler with ConfigurePrimaryHttpMessageHandler or register a stub HttpMessageHandler so no real calls leave..NET 8 introduced TimeProvider; Microsoft.Extensions.TimeProvider.Testing provides FakeTimeProvider with Advance(). Inject TimeProvider instead of calling DateTime.UtcNow, then replace it in tests.
using var factory = new WebApplicationFactory<Program>()
.WithWebHostBuilder(b => b.UseDefaultServiceProvider(o => { o.ValidateOnBuild = true; o.ValidateScopes = true; }));
_ = factory.Services; // builds the host; throws on missing registrations
It catches missing registrations and scoped-in-singleton problems that only appear in non-Development environments where validation is off by default.
A container in a unit test hides which dependencies matter, makes tests slower, and lets the test pass even if the constructor grows. Direct construction makes the compiler tell you when dependencies change.
TimeProvider, using FakeTimeProvider.Advance(TimeSpan.FromDays(31)).WebApplicationFactory test that replaces IEmailSender with an in-memory outbox and asserts one email was "sent".Replace when two IEmailSenders are registered and check which ones IEnumerable<IEmailSender> returns; then use RemoveAll.An integration test that swaps only external boundaries, and a container-free unit test.
// Program.cs (end of file): expose Program to the test project.
public partial class Program;
namespace Orders.Tests;
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Time.Testing;
using Xunit;
public sealed class PlaceOrderTests(WebApplicationFactory<Program> factory)
: IClassFixture<WebApplicationFactory<Program>>
{
[Fact]
public async Task Placing_an_order_sends_one_confirmation_email()
{
var outbox = new InMemoryEmailSender();
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 11, 19, 9, 0, 0, TimeSpan.FromHours(11)));
var client = factory.WithWebHostBuilder(b => b.ConfigureTestServices(services =>
{
// Runs after Program.cs registrations; RemoveAll makes the swap explicit.
services.RemoveAll<IEmailSender>();
services.AddSingleton<IEmailSender>(outbox);
services.RemoveAll<TimeProvider>();
services.AddSingleton<TimeProvider>(clock);
})).CreateClient();
var response = await client.PostAsJsonAsync("/orders", new { CustomerEmail = "[email protected]", Total = 99.95m });
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.Single(outbox.Sent);
}
}
// A fake: a real, simple implementation we can assert against.
public sealed class InMemoryEmailSender : IEmailSender
{
public List<(string To, string Subject)> Sent { get; } = [];
public Task SendAsync(string to, string subject, CancellationToken ct)
{
Sent.Add((to, subject));
return Task.CompletedTask;
}
}
// Unit test: no container, the constructor is the seam.
[Fact]
public void Order_is_overdue_after_30_days()
{
var clock = new FakeTimeProvider(DateTimeOffset.Parse("2026-10-01T00:00:00Z"));
var sut = new OverdueChecker(clock);
clock.Advance(TimeSpan.FromDays(31));
Assert.True(sut.IsOverdue(DateTimeOffset.Parse("2026-10-01T00:00:00Z")));
}
ServiceCollection in unit tests. Why it is wrong: it hides dependencies and slows tests; the class should be constructible directly. Instead: new Sut(fakes...).Replace when several implementations are registered. Why it is wrong: it only removes the first, so IEnumerable<T> consumers still get the real one. Instead: RemoveAll<T>() then add the fake.DateTime.UtcNow directly. Why it is wrong: time-dependent logic can't be tested deterministically. Instead: inject TimeProvider and use FakeTimeProvider.ValidateOnBuild/ValidateScopes are off by default in other environments. Instead: add a test that builds the host with both enabled.The point of DI in tests isn't mocking; it's controlling the boundaries. I aim for many fast unit tests with direct construction, a handful of integration tests per feature through WebApplicationFactory that keep my own code real, and one composition-root test that fails CI on any missing or mis-scoped registration. That mix catches the bugs that actually reach production: wiring, configuration and SQL behaviour.
For shared setup I subclass WebApplicationFactory<Program> and override ConfigureWebHost, calling builder.ConfigureTestServices(...) and UseEnvironment("Testing") there, so every test class gets the same boundaries swapped. Scoped services such as DbContext for seeding are resolved inside using var scope = factory.Services.CreateScope(), keeping lifetimes the same as production. These tests are a quality gate in the PR pipeline, not an optional nightly job: they are the only automated check that the real container, configuration binding and middleware order still work together.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Direct construction with fakes | Unit tests of domain and application logic | Very low | Testing wiring or middleware |
WebApplicationFactory + ConfigureTestServices |
Endpoint and pipeline behaviour | Seconds per test class | Pure logic tests |
| Mocks (Moq, NSubstitute) | Verifying boundary interactions | Brittle if overused | State you can assert on a fake |
| Testcontainers database | Queries, transactions, migrations | Docker, slower CI | Logic that doesn't touch the database |
I'd turn Program.cs back into a composition root and move endpoints into feature folders. Each feature gets one extension method, MapOrderEndpoints(this IEndpointRouteBuilder app), that creates a MapGroup("/orders") and applies shared metadata once: RequireAuthorization, WithTags, endpoint filters, rate limiting. Handlers become named static methods that return Results<Ok<OrderDto>, NotFound> built with TypedResults, so every outcome is compile-time checked and appears in the OpenAPI document. Then testing is easy at two levels: unit tests call the static handler directly and assert the result type, and integration tests use WebApplicationFactory<Program> with ConfigureTestServices to swap the database or external clients. The trade-off: a little more structure up front, in exchange for endpoints that stay readable at 80 or 800.
IServiceCollection is just a list of ServiceDescriptors: a service type, an implementation (type, instance or factory delegate) and a lifetime. AddSingleton, AddScoped and AddTransient append to that list.
T gives you the last registration, while injecting IEnumerable<T> gives you all of them in registration order.TryAdd* adds only if nothing is registered for that service type, which is how libraries provide overridable defaults. TryAddEnumerable adds only if that exact implementation isn't already there.Replace swaps the first registration; RemoveAll clears them.The trade-off: ordering makes overrides easy but silent, so registration order bugs are easy to write and hard to see.
Inversion of control (IoC) is the broad idea that something else controls the flow and object creation: the framework calls your code, not the other way round. Dependency injection (DI) is a specific IoC technique: a class declares what it needs, usually as constructor parameters, and a caller or container supplies it. The Dependency Inversion Principle (DIP) is the "D" in SOLID: high-level code depends on abstractions it owns, and low-level details implement them.
In ASP.NET Core you register services on builder.Services in Program.cs (the composition root), and the built-in container builds controllers, endpoints and middleware with their dependencies.
The trade-off: DI buys testability and replaceable parts at the cost of indirection; it is a tool, DIP is the design goal.
How to tell it (STAR)
**S:** At [company] our order API had a green integration suite, yet a release broke order placement in staging with a missing DI registration. **T:** I was asked to work out why the tests didn't catch it and stop it recurring. **A:** I found the tests mocked our own validators and services in ConfigureTestServices, so the new validator's registration was never exercised, and ValidateOnBuild was off outside Development. I rewrote the tests to replace only payments, email and the clock, and added a composition-root test that builds the host with ValidateOnBuild and ValidateScopes on. **R:** The suite got about [30] seconds slower, but it caught the next [two] missing registrations in CI, and we've had [zero] DI-related staging failures since.
Last updated 23 Nov 2026.