6.2 — The Built-in Container: IServiceCollection and IServiceProvider¶
← Roadmap · Section: 6. Dependency Injection Prev: 6.1 IoC and DI · Next: 6.3 Service lifetimes
Markers: 🔥 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
ASP.NET Core has a DI container built in. It has two halves, split by builder.Build().
IServiceCollection— the shopping list. You add registrations to it, beforeBuild().IServiceProvider— the built container. You resolve objects from it, afterBuild().- Once
Build()runs, the collection is frozen. Adding more throws.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
IServiceCollection |
an interface | The list of registrations. builder.Services is one. Write-only in practice. |
IServiceProvider |
an interface | The built container. Resolves objects. app.Services is one. |
ServiceDescriptor |
a class | One registration: service type, implementation type, and lifetime. |
| Service type | the key | What you ask for — usually an interface, like IEmailSender. |
| Implementation type | the value | What you get — the concrete class, like SendGridEmailSender. |
AddTransient<T> |
a method | Register with transient lifetime — new instance every time. |
AddScoped<T> |
a method | Register with scoped lifetime — one per request. |
AddSingleton<T> |
a method | Register with singleton lifetime — one for the app. |
GetService<T>() |
a method | Resolve, returning null if not registered. |
GetRequiredService<T>() |
a method | Resolve, throwing if not registered. Preferred. |
builder.Build() |
a method | Builds the provider from the collection and freezes it. |
| Root provider | the top-level IServiceProvider |
app.Services. Has no request scope. |
The concept¶
Two objects, two phases¶
Everything about the container follows from one split:
var builder = WebApplication.CreateBuilder(args);
// ═══ PHASE 1 — IServiceCollection ═══
// "Here is what exists." Adding registrations.
builder.Services.AddScoped<IOrderService, OrderService>();
var app = builder.Build(); // ← collection frozen, provider created
// ═══ PHASE 2 — IServiceProvider ═══
// "Give me one." Resolving objects.
var service = app.Services.GetRequiredService<IOrderService>();
A picture: a shopping list, then a kitchen.
IServiceCollection is the list — you write on it, you do not cook from it.
IServiceProvider is the stocked kitchen — you take things out, you do not add to it.
builder.Build() is going shopping. After that, the list is done.
That is why adding a service after Build() throws with "Services cannot be added after
the application is built". It is not an arbitrary restriction — the container has already been
constructed from the registrations, and changing them afterwards would leave it inconsistent.
How it works¶
The simple version — registering¶
Three lifetimes, three methods (6.3):
builder.Services.AddTransient<IEmailFormatter, EmailFormatter>(); // new every time
builder.Services.AddScoped<IOrderRepository, OrderRepository>(); // one per request
builder.Services.AddSingleton<IPriceCache, PriceCache>(); // one per app
Each has several overloads:
// Interface → implementation. The common case.
builder.Services.AddScoped<IOrderService, OrderService>();
// Concrete type only — register a class as itself
builder.Services.AddScoped<OrderService>();
// A factory — when construction needs logic
builder.Services.AddScoped<IOrderService>(sp =>
{
var repo = sp.GetRequiredService<IOrderRepository>();
return new OrderService(repo, enableCache: true);
});
// An instance you already made. ⚠️ Singleton only, and YOU own disposal — see 6.10.
builder.Services.AddSingleton<IClock>(new SystemClock());
Resolving¶
// Preferred — throws a clear exception if not registered
var service = provider.GetRequiredService<IOrderService>();
// Returns null if not registered — for genuinely optional dependencies
var optional = provider.GetService<IFeatureFlag>();
// All registrations for one type — see 6.7
var validators = provider.GetServices<IValidator>();
⚠️ Prefer GetRequiredService. GetService returning null means a missing registration
surfaces later as a NullReferenceException somewhere unrelated, whereas
GetRequiredService fails immediately and names the missing type.
⚠️ You rarely call these at all¶
This is worth stating plainly: in normal application code you do not touch
IServiceProvider. You put dependencies in a constructor and the container supplies them.
// ✓ Normal — the container resolves the graph for you
public class OrdersController(IOrderService orders) : ControllerBase { }
// ✗ Reaching into the container manually — the service locator anti-pattern
public class OrdersController(IServiceProvider provider) : ControllerBase
{
public IActionResult Get()
{
var orders = provider.GetRequiredService<IOrderService>(); // don't
}
}
The second hides dependencies — the constructor no longer tells you what the class needs — and turns a missing registration from a startup error into a runtime one. See 6.9.
Legitimate reasons to touch the provider directly: creating a scope in a background service
(6.5), startup tasks in Program.cs, and writing a factory registration.
How it actually works — what a registration is¶
Each call adds a ServiceDescriptor — a small record of three things:
public class ServiceDescriptor
{
public Type ServiceType { get; } // IOrderService
public Type? ImplementationType { get; } // OrderService
public ServiceLifetime Lifetime { get; } // Scoped
// ...plus factory and instance variants
}
The collection is literally an IList<ServiceDescriptor>, which has two consequences worth
knowing.
Registering the same service type twice does not replace — it appends. Both descriptors are in the list:
builder.Services.AddScoped<IEmailSender, SmtpEmailSender>();
builder.Services.AddScoped<IEmailSender, SendGridEmailSender>();
// Resolving IEmailSender gives you SendGridEmailSender — the LAST one wins
// Resolving IEnumerable<IEmailSender> gives you BOTH
Last-one-wins is the rule for a single resolve. That is deliberate and useful — it is how you
override a framework default — but it also means an accidental duplicate registration silently
changes behaviour with no warning. See 6.6 for TryAdd, which
exists precisely to avoid that.
And you can inspect or modify the list before Build():
// Replace an existing registration
builder.Services.RemoveAll<IEmailSender>();
builder.Services.AddScoped<IEmailSender, FakeEmailSender>();
// Or replace in one call
builder.Services.Replace(
ServiceDescriptor.Scoped<IEmailSender, FakeEmailSender>());
That is exactly how WebApplicationFactory swaps real services for fakes in integration tests —
20.7.
The deeper detail — validation options¶
Two settings turn silent DI bugs into startup failures:
builder.Host.UseDefaultServiceProvider(options =>
{
options.ValidateScopes = true; // catch captive dependencies
options.ValidateOnBuild = true; // catch unresolvable registrations
});
ValidateScopes detects a scoped service injected into a singleton — the captive dependency
problem (6.4).
ValidateOnBuild walks every registration at startup and confirms it can actually be
resolved, so a missing dependency fails immediately rather than on the first request that needs
it.
⚠️ Both are enabled by default in Development only. That is precisely why these bugs reach production — the environment that would have caught them is the one you do not deploy. Enabling them everywhere costs a little startup time and is almost always worth it.
Code¶
A realistic Program.cs showing the range of registration styles:
var builder = WebApplication.CreateBuilder(args);
// Simple interface → implementation
builder.Services.AddScoped<IOrderRepository, EfOrderRepository>();
builder.Services.AddScoped<IOrderService, OrderService>();
// Framework helpers that register several things at once
builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>(o => // registers as SCOPED
o.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
builder.Services.AddHttpClient<IPaymentGateway, StripeGateway>();
// A factory — construction needs a decision
builder.Services.AddSingleton<IStorageProvider>(sp =>
{
var config = sp.GetRequiredService<IConfiguration>();
return config["Storage:Provider"] switch
{
"azure" => new AzureBlobStorage(config["Storage:ConnectionString"]!),
"s3" => new S3Storage(config["Storage:Bucket"]!),
_ => new LocalFileStorage(config["Storage:Path"]!)
};
});
// Options — typed configuration, not raw strings
builder.Services.Configure<OrderOptions>(builder.Configuration.GetSection("Orders"));
// Fail fast on bad wiring, in every environment
builder.Host.UseDefaultServiceProvider(o =>
{
o.ValidateScopes = true;
o.ValidateOnBuild = true;
});
var app = builder.Build();
// Startup work — needs a scope, because there is no request scope here. See 6.5.
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync();
}
app.Run();
Two things in that file are worth calling out.
AddDbContext registers as scoped — you do not choose the lifetime, and that is deliberate
(13.2).
The startup scope is not optional. AppDbContext is scoped and app.Services is the root
provider with no ambient scope, so resolving it directly throws.
Interview questions¶
Q: What is the difference between IServiceCollection and IServiceProvider?
They are the two halves of the container, split by builder.Build(). IServiceCollection is the
list of registrations — you add to it during the first phase of Program.cs, saying what exists
and with what lifetime. IServiceProvider is the built container that actually resolves objects,
available after Build(). Once Build() runs the collection is frozen, which is why adding a
service afterwards throws — the provider has already been constructed from those registrations.
Q: What happens if you register the same interface twice?
Both registrations stay in the list, because the collection is genuinely a list of descriptors
rather than a dictionary. Resolving the single service gives you the last one registered,
which is how you deliberately override a framework default. Resolving IEnumerable<T> of that
type gives you all of them. The risk is that an accidental duplicate silently changes which
implementation you get, with no warning — which is why TryAdd exists, to register only if
nothing is there already.
Q: When would you resolve from IServiceProvider directly?
Rarely, and it is worth being suspicious when you see it. In normal application code you put
dependencies in the constructor and let the container build the graph. The legitimate cases are
creating a scope in a background service or a singleton that needs scoped work, running startup
tasks in Program.cs before the app starts, and writing a factory registration. Injecting
IServiceProvider into a controller to pull services out on demand is the service locator
anti-pattern — it hides what the class depends on and turns a missing registration from a startup
error into a runtime one.
Q: What do ValidateScopes and ValidateOnBuild do?
ValidateScopes detects captive dependencies — a scoped service injected into a singleton, which
pins one request-lifetime object for the life of the application. ValidateOnBuild walks every
registration at startup and verifies it can actually be resolved, so a missing dependency fails
immediately instead of on the first request that hits that code path. The important detail is
that both are enabled by default only in Development, which is exactly why those bugs survive
into production. Turning them on in all environments costs a little startup time and catches a
genuinely painful class of error.
Traps ⚠️¶
- Adding services after
builder.Build()throws. The collection is frozen. - Duplicate registrations silently change behaviour — last one wins for a single resolve.
GetServicereturns null, so a missing registration surfaces later as a null reference. PreferGetRequiredService.- Resolving a scoped service from
app.Servicesthrows. Create a scope first (6.5). - Injecting
IServiceProviderinto your classes is the service locator anti-pattern (6.9). ValidateScopesis Development-only by default, so captive dependencies reach production.- An instance passed to
AddSingleton(instance)is not disposed by the container — you own it (6.10).
Related¶
- 6.1 IoC and DI — the principle behind this
- 6.3 Service lifetimes — transient, scoped, singleton
- 6.5 Scopes — why startup code needs
CreateScope - 6.6 Registration APIs —
TryAddand keyed services - 6.9 Injection styles — the service locator problem
- 4.3 Program.cs — the two phases
- 20.7 Integration testing — replacing registrations