Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 52 ยท Dependency Injection, Configuration and Logging

Dependency Injection in ASP.NET Core

See how ASP.NET Core creates a service scope per request, where you can inject services, how lifetimes behave in a web app and how to avoid captive dependencies.

Dependency injection (DI) is not an add-on in ASP.NET Core; the framework itself is built from services. Kestrel, routing, logging, configuration and the JSON serializer are all registered in one container, and your own classes join them. Every endpoint, middleware component, filter and hosted service can ask for what it needs and receive it.

If the idea is new, read the C# lessons on dependency injection first. They explain registration, the three lifetimes and the container itself in plain .NET. This lesson does not repeat them. It answers the web-specific questions: when is a scope created, where can you inject, what does a lifetime really mean during a request, and which mistakes bite web apps in particular?

The container in a web app

WebApplication.CreateBuilder() gives you builder.Services, an IServiceCollection that already contains hundreds of framework registrations. You add yours, call Build(), and the result is the root service provider, which lives as long as the application.

For each incoming request, the framework creates a child scope from that root provider and stores its provider in HttpContext.RequestServices. When the response is finished, the scope is disposed, which also disposes every IDisposable created in it.

flowchart TB
    ROOT["Root provider<br/>(singletons live here)"]
    ROOT --> S1["Request 1 scope<br/>scoped services #1"]
    ROOT --> S2["Request 2 scope<br/>scoped services #2"]
    S1 --> T1["transient: new each time asked"]
    S2 --> T2["transient: new each time asked"]

Singletons come from the root; scoped services are shared inside one request's scope; transients are created on every request for the service.

That picture explains the lifetimes in a web app:

Lifetime Instances in a web app Typical use
Singleton One for the whole process Caches, configuration holders, HttpClient factories, clocks
Scoped One per HTTP request Per-request state, a unit of work, an EF Core DbContext
Transient A new instance every time the service is requested Small stateless helpers

Scoped is the lifetime that makes the web special. Every component handling the same request (a middleware, the endpoint, the services they call) gets the same scoped instance, and a different request gets a different one.

Where you can inject

You do not call the container yourself in most places. The framework resolves services for you at these points:

  • Minimal API handlers: add the service as a parameter. The binder recognizes registered types automatically (see parameter binding).
  • Controllers: through the constructor (covered in controllers and actions).
  • Middleware: a convention-based middleware class takes singleton-safe services in its constructor (it is created once) and can take scoped services as extra parameters of InvokeAsync. Factory-based IMiddleware classes are created per request and may use scoped services in the constructor (writing middleware).
  • Inline middleware (app.Use(...)): use context.RequestServices.
  • Endpoint filters, authorization handlers, hosted services, options configuration: constructor injection, with lifetime rules that come from how each is created.

When you have no better option, context.RequestServices.GetRequiredService<T>() resolves a service from the current scope. It is a service locator, so prefer parameters when you can, but it is perfectly fine inside inline middleware.

Seeing the lifetimes during requests

The next program registers one service of each lifetime and a middleware that also asks for the scoped service. Every instance takes a number from a counter when it is created, so you can see exactly who got what. Two requests are sent; look for the pattern.

C# Singleton, scoped and transient across two requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The result matches the table. The singleton stays #1 in both requests. In each request the two scoped parameters and the middleware all received the same number, and the second request got a new one. Each transient parameter was a different object. And the scoped instances were disposed after their requests finished, which is how a DbContext returns its connection to the pool without you writing any cleanup code.

Captive dependencies

A service must never outlive the things it depends on. A captive dependency appears when a longer-lived service holds a shorter-lived one: a singleton that takes a scoped service in its constructor keeps that one instance forever, long after its request has ended. The scoped service stops being "per request" and becomes shared by all requests, concurrently. If it is a DbContext, which is not thread-safe, you get random, hard-to-reproduce failures.

The rule of thumb is simple: a service may depend only on services with the same or a longer lifetime. Transient may take anything, scoped may take scoped and singleton, singleton may take only singletons.

ASP.NET Core can catch this mistake for you. Two options of the service provider control it:

  • ValidateScopes throws when a scoped service is resolved from the root provider, or consumed by a singleton.
  • ValidateOnBuild checks every registration when Build() runs instead of waiting for the first use.

Both are turned on automatically in the Development environment and off otherwise, because validating costs startup time. That is a good reason to run your integration tests in Development, or to enable them explicitly everywhere.

C# Catching a captive dependency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

With validation off, the app starts happily and the bug hides: the singleton keeps one DbSession for the entire life of the process. With validation on, the mistake is reported while building the app, with a message naming both services. Fixing it means changing a lifetime (make the cache scoped or the session singleton-safe) or, when the singleton genuinely needs scoped work, creating a scope on purpose, as the next section shows.

The classic real-life version is a singleton or a BackgroundService that takes a DbContext in its constructor. Do not register the DbContext as a singleton; inject IServiceScopeFactory and create a scope for each unit of work. Background services develops this pattern.

Creating scopes yourself

Outside a request there is no scope. Long-lived code that needs scoped services, like a timer-driven job, creates one explicitly:

C#
using IServiceScope scope = scopeFactory.CreateScope();
var session = scope.ServiceProvider.GetRequiredService<DbSession>();
// use it, then the scope (and its disposables) are cleaned up

Prefer CreateAsyncScope() when any service may implement IAsyncDisposable. Never resolve scoped services from the root provider (app.Services) without a scope: that is the same captive mistake, only worse.

Factories, keys and other registration forms

Registration can do more than AddScoped<TService, TImplementation>():

  • Factory registration runs your lambda with the provider whenever an instance is needed. Use it when construction needs configuration or a choice made at runtime.
  • Keyed services (since .NET 8) register several implementations of one interface under different keys. Consumers select one with [FromKeyedServices("key")], in minimal API parameters and constructors alike.
  • TryAdd registers only if the service is not registered yet, which is how libraries provide overridable defaults.
  • Open generics (AddSingleton(typeof(IRepository<>), typeof(Repository<>))) cover every closed type at once.

The C# tutorial shows these in plain .NET code, in registration styles and in the keyed services section. The next example uses factory and keyed registration inside a web app, and shows how a middleware can resolve a scoped service by asking for it through RequestServices.

C# Factory registration and keyed services

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The unkeyed IShippingRate is a factory that reads the configuration and hands out one of the keyed instances, so endpoints that just want "the shipping rate" stay ignorant of the choice. Endpoints that care about a specific variant use the key. Note the scoped factory returns singletons, which is allowed: shorter-lived services may depend on longer-lived ones.

Habits for web apps

  • Put registration in extension methods such as services.AddBilling(), one per feature, so Program.cs stays readable.
  • Depend on interfaces you own at boundaries you want to fake in tests. A fake replaces a registration with one line.
  • Keep constructors cheap. They run on the request path; do I/O in methods.
  • Do not store HttpContext or scoped services in singletons. Pass the values you need as arguments.
  • Run with scope validation during testing. It turns silent lifetime bugs into build errors.
  • Prefer parameters over RequestServices. Locator calls hide dependencies and are harder to test.

The same container also feeds configuration to your classes. That is the topic of the next lesson, configuration and the options pattern.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In an ASP.NET Core app, how many instances of a scoped service are created for one HTTP request, no matter how many components ask for it?

    A scope is created per request, and a scoped service is created once inside it, so middleware, endpoint and services all share it. Another request gets its own.
  2. 2. What is a captive dependency?

    For example, a singleton that receives a scoped DbContext in its constructor keeps that one instance for the life of the app and shares it between requests.
  3. 3. When are ValidateScopes and ValidateOnBuild enabled by default?

    They cost startup time, so the default host enables them in Development. You can enable them explicitly everywhere with UseDefaultServiceProvider.
  4. 4. A singleton background worker needs a scoped service for each job. What should it do?

    Creating a scope per unit of work gives the job its own scoped instances and disposes them afterwards, without capturing anything.
  5. 5. How do you pick one of several implementations registered with AddKeyedSingleton in a minimal API handler?

    The [FromKeyedServices] attribute tells the binder to resolve the parameter by key. GetRequiredKeyedService does the same imperatively.

Summary

  • ASP.NET Core is built on DI: builder.Services is the container, Build() creates the root provider, and each request gets a child scope in HttpContext.RequestServices.
  • Singleton means one per process, scoped means one per request, transient means one per request for the service; scoped instances are disposed when the response ends.
  • Inject through endpoint parameters, constructors, InvokeAsync parameters of middleware, or RequestServices in inline middleware.
  • A service may depend only on services with the same or a longer lifetime; captive dependencies are the classic bug.
  • Scope validation catches captive dependencies and is on by default only in Development; use IServiceScopeFactory for scoped work in long-lived code.
  • Factory and keyed registrations choose implementations at runtime or by name without changing consumers.

Next: Configuration and the Options Pattern