skip to content

In ASP.NET Core, why is the DbContext that AddDbContext registers scoped, and what breaks if you pass ServiceLifetime.Transient or ServiceLifetime.Singleton instead?

level: middleimportance: must knowfreq 70%

answer

  1. one change tracker per unit of work
  2. DbContext is not thread-safe
  3. contextLifetime parameter on AddDbContext
  4. "A second operation was started on this context"
  5. transient splits one request's SaveChanges

basics

~20 s

Scoped gives each request exactly one context, so every service in that request shares one change tracker and one SaveChangesAsync. Transient splits a request's work across trackers; singleton shares one non-thread-safe context across concurrent requests.

solid answer

~40 s

A `DbContext` is a unit of work: it tracks the entities a request loads and writes them in one `SaveChangesAsync`, and it is not thread-safe. Scoped matches both facts: one request, one context, shared by every service in that request, never used by two requests at once. If I pass `contextLifetime: ServiceLifetime.Transient`, each injection point gets its own context, so a `BookingService` that adds a booking and a `CapacityService` that decrements seats in the same request track changes in different contexts and one `SaveChangesAsync` saves only half. If I pass `ServiceLifetime.Singleton`, EF Core also makes the options singleton and one context serves every request: concurrent requests trip EF's concurrency detector with an `InvalidOperationException`, the change tracker keeps growing, and users see stale tracked data.

go deeper

for a junior

Remember that the default is Scoped and that a DbContext must not be shared between requests because it is not thread-safe.

for a middle

Walk through the change tracker and unit of work: why two services in one request must share a context, and how transient silently drops one service's changes.

for a senior

Diagnose the symptoms of a wrong lifetime in production, from concurrency exceptions and stale reads to memory growth, and reach for AddDbContextFactory when a request needs parallel work.

for a principal

Treat context lifetime as an architectural invariant: decide where explicit factories are allowed and how reviews catch lifetime overrides before they ship.

## What a DbContext holds An EF Core `DbContext` is not a connection wrapper you can share freely. Each instance carries: - a **change tracker** that remembers every entity it loaded or was given, with original and current values; - an **identity map**, so querying the same key twice returns the same object; - a database connection it opens and releases as queries run, and optionally a transaction; - a concurrency detector that throws when two operations overlap. EF Core states that it does not support multiple parallel operations on the same `DbContext` instance, from parallel async queries or from several threads. ## Why scoped fits a web request `AddDbContext<TContext>` has two optional parameters, `contextLifetime` and `optionsLifetime`, and both default to `ServiceLifetime.Scoped`. ASP.NET Core creates one dependency-injection scope per HTTP request, so the default gives you: 1. **One unit of work per request.** The handler, the controller and every service they call receive the same instance, so the entities one service changes are visible to the next, and a single `SaveChangesAsync` writes them together. 2. **No sharing between requests.** A concurrent request has its own scope and its own context, so the non-thread-safe instance is never used from two requests at once. 3. **Bounded memory.** The change tracker lives only as long as the request; the scope disposes the context when the response completes. ## What transient breaks `builder.Services.AddDbContext<BookingDbContext>(o => ..., contextLifetime: ServiceLifetime.Transient)` is legal and EF documents it for code that deliberately wants independent contexts. In a normal request pipeline it breaks the unit of work. Take a gym-class booking endpoint: ```csharp app.MapPost("/classes/{id:int}/bookings", async ( int id, BookingRequest req, BookingService bookings, SeatService seats) => { await seats.ReserveSeatAsync(id); // changes GymClass.SeatsLeft var booking = await bookings.AddAsync(id, req.MemberId); await bookings.SaveAsync(); // calls db.SaveChangesAsync() return Results.Created($"/bookings/{booking.Id}", booking); }); ``` With a scoped context, `SeatService` and `BookingService` share one context, so the seat decrement and the new booking are saved together. With a transient context each service holds its own instance; `SaveAsync` saves only the booking, and the seat change is silently dropped when `SeatService`'s context is disposed. Each transient context also opens its own connection when it runs a query. ## What singleton breaks Passing `ServiceLifetime.Singleton` makes EF Core force `optionsLifetime` to singleton as well, and one context then serves every request for the life of the process: - two requests that query at the same moment make EF throw `InvalidOperationException`: "A second operation was started on this context instance before a previous operation completed"; when the overlap is not detected, behaviour is undefined; - the change tracker never clears, so memory grows and every query pays to reconcile with thousands of tracked entities; - the identity map returns entities loaded hours ago, so one member sees seat counts another request already changed; - a failed `SaveChangesAsync` leaves pending changes behind that the next, unrelated request will try to save. ## What the scope does at the end of the request The scoped default also settles **cleanup**. When the response completes, ASP.NET Core disposes the request's scope, and the scope disposes the context. Disposal releases anything the context still holds, such as an open connection, and drops every tracked entity, so nothing from one member's booking leaks into the next request. Code that keeps a reference past that point, for example a fire-and-forget `Task.Run` started inside the handler, finds the context disposed and gets an `ObjectDisposedException`; work that must outlive the request needs its own scope or a factory-made context, not the request's instance. The same rule explains why changing `optionsLifetime` alone rarely matters: the options object is immutable configuration. EF Core forces it to `Singleton` only when the context itself is singleton, and you set it yourself mainly to share the options with a singleton factory. ## Choosing the lifetime | Lifetime | Instances in one request | Shared across requests | Typical outcome | |---|---|---|---| | Scoped (default) | one | no | one unit of work per request | | Transient | one per injection point | no | split change tracking, extra connections | | Singleton | one for the app | yes | concurrency exceptions, stale data, growing memory | Keep the default in web code. When one request genuinely needs several independent contexts, for example to run two queries in parallel, register `AddDbContextFactory` and create short-lived contexts explicitly rather than changing the lifetime for the whole app.

  • A handler in the gym-booking API starts two EF Core queries and awaits them with Task.WhenAll on the injected context. What happens, and what is the fix?
    Both queries run on the same scoped `DbContext`, so EF Core's concurrency detector throws `InvalidOperationException` ("A second operation was started on this context instance..."). Either await the queries one after the other, or register `AddDbContextFactory` and give each parallel query its own short-lived context with `await using`, then combine the results.
  • If you pass contextLifetime: ServiceLifetime.Singleton to AddDbContext, what happens to the options lifetime?
    EF Core overrides it: when `contextLifetime` is `Singleton`, `AddDbContext` sets `optionsLifetime` to `Singleton` too, because a singleton context cannot depend on scoped options. The registration then succeeds, which is exactly why the shared-context defect reaches production instead of failing at startup.

A scoped DbContext is like the order pad a waiter carries for one table: everyone at the table adds to the same pad, the kitchen gets one order, and the pad is thrown away when the table leaves. Transient hands each diner a separate pad and only one reaches the kitchen; singleton makes every table in the restaurant scribble on a single pad at once.

  • DbContext is thread-safe, so one instance can serve all concurrent requests.
  • Transient is safer because every class gets a fresh, clean context.
  • Scoped means the context lives for the user's whole login session.
  • A singleton context is faster because the model is built only once.
  • Two services in one request each get their own scoped context.