skip to content

DbContext per Request

AddDbContext gives each HTTP request its own scoped DbContext, and AddDbContextFactory serves code that runs outside a request. Interviewers check you never hold a context in a singleton.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

In ASP.NET Core 10, how do you register an EF Core DbContext with a connection string from configuration, and what lifetime does it get?

level: juniorimportance: must knowfreq 80%

answer

  1. registered on builder.Services before Build()
  2. ConnectionStrings section in appsettings.json
  3. constructor takes DbContextOptions<TContext>
  4. contextLifetime defaults to Scoped
  5. request scope disposes it

basics

~10 s

Call builder.Services.AddDbContext<BookingDbContext>(o => o.UseNpgsql(builder.Configuration.GetConnectionString("Bookings"))) before Build(). AddDbContext registers the context Scoped by default, so every HTTP request gets its own instance, disposed when that request ends.

solid answer

~40 s

I register it in `Program.cs` with `builder.Services.AddDbContext<BookingDbContext>(options => options.UseNpgsql(connectionString))`, where `connectionString` comes from `builder.Configuration.GetConnectionString("Bookings")`, which reads `ConnectionStrings:Bookings` from appsettings, user secrets or an environment variable. The context needs a constructor that takes `DbContextOptions<BookingDbContext>` and passes it to the base class. `AddDbContext` defaults `contextLifetime` and `optionsLifetime` to `ServiceLifetime.Scoped`, so ASP.NET Core creates one context per request, hands the same instance to every service and handler in that request, and disposes it when the request scope ends. I then inject it into a Minimal API handler parameter or a controller constructor and never `new` it or dispose it myself. The templates also fail fast with `?? throw new InvalidOperationException(...)` when the connection string is missing.

code

json · 5 lines
json
{
  "ConnectionStrings": {
    "Bookings": "Host=localhost;Database=gym_bookings;Username=gym_app"
  }
}

go deeper

for a junior

Write the AddDbContext line from memory, name GetConnectionString and the ConnectionStrings section, and say the default lifetime is Scoped: one context per HTTP request.

for a middle

Explain what AddDbContext registers besides the context, why the class needs a DbContextOptions<TContext> constructor, and why disposing an injected context yourself breaks the rest of the request.

for a senior

Show how the same registration runs unchanged across environments with secrets outside source control, and how a missing connection string should fail at startup rather than on the first query.

for a principal

Frame the per-request context as a team convention: where connection strings live, who may change lifetimes, and how code outside requests is steered to a factory instead.

## The registration in Program.cs An EF Core `DbContext` reaches an ASP.NET Core app through dependency injection. You register it once on `builder.Services`, before `builder.Build()`, with the `AddDbContext<TContext>` extension method from the `Microsoft.EntityFrameworkCore` package, and you choose the database provider inside the options callback. For a gym-class booking API on PostgreSQL: ```csharp var builder = WebApplication.CreateBuilder(args); var connectionString = builder.Configuration.GetConnectionString("Bookings") ?? throw new InvalidOperationException("Connection string 'Bookings' not found."); builder.Services.AddDbContext<BookingDbContext>(options => options.UseNpgsql(connectionString)); var app = builder.Build(); app.MapGet("/classes/{id:int}", async (int id, BookingDbContext db) => await db.GymClasses.FindAsync(id) is { } gymClass ? Results.Ok(gymClass) : Results.NotFound()); ``` The same null-check-and-throw shape is what the ASP.NET Core MVC template with Individual authentication writes for its `DefaultConnection` string, so a missing setting fails at startup instead of on the first query. ## Where the connection string comes from `GetConnectionString("Bookings")` is shorthand for reading the configuration key `ConnectionStrings:Bookings`. Because `WebApplication.CreateBuilder` layers several configuration sources, the same key can be supplied by: - `appsettings.json` or `appsettings.Development.json`, under a `ConnectionStrings` object; - user secrets during local development, so a password never lands in source control; - an environment variable named `ConnectionStrings__Bookings` in a container or hosting platform; - any other provider you add, such as a secrets vault. The DbContext code does not change between environments; only the configuration does. ## What AddDbContext puts in the container `AddDbContext` is more than one registration. With its default arguments it adds: | Service | Lifetime | Notes | |---|---|---| | `BookingDbContext` | Scoped | `contextLifetime` defaults to `ServiceLifetime.Scoped` | | `DbContextOptions<BookingDbContext>` | Scoped | `optionsLifetime` defaults to `ServiceLifetime.Scoped` | | `DbContextOptions` (non-generic) | Scoped | forwards to the generic options | For the options to reach the context, the context class must declare a constructor that accepts `DbContextOptions<BookingDbContext>` and passes it to `base(options)`. If you pass an options callback but the class only has a parameterless constructor, `AddDbContext` throws an `ArgumentException` at registration time explaining that the configuration would never be used. A primary constructor works fine: ```csharp public class BookingDbContext(DbContextOptions<BookingDbContext> options) : DbContext(options) { public DbSet<GymClass> GymClasses => Set<GymClass>(); public DbSet<Booking> Bookings => Set<Booking>(); } ``` ## How one request uses it ASP.NET Core opens a dependency-injection **scope** for every HTTP request. Because the context is **scoped**: 1. The first time anything in the request asks for `BookingDbContext`, the scope creates one instance. 2. Every other consumer in that request, whether a handler parameter, a controller constructor or a `BookingService` the handler calls, receives the **same** instance, so they share one change tracker and one `SaveChangesAsync`. 3. When the response completes, the request scope is disposed and disposes the context with it, releasing anything it still holds, such as an open connection or transaction. A concurrent request gets its own scope and its own context, which matters because a `DbContext` is not thread-safe. ## More than one context A booking API may keep reporting data in a second database. Each context type gets its own `AddDbContext` call and its own connection string name, for example `GetConnectionString("Reporting")` for a `ReportingDbContext`. Two rules keep that working: - each context's constructor takes the **generic** `DbContextOptions<TContext>` for its own type; with the non-generic `DbContextOptions`, EF Core cannot tell the two registrations apart and complains that the options passed must be a `DbContextOptions<TContext>`; - each context is still scoped, so a request that touches both gets exactly one instance of each, disposed together at the end of the request. Where the registration lives matters too. Keeping every `AddDbContext` call in `Program.cs`, or in one `AddPersistence(this IServiceCollection services, IConfiguration config)` extension method that `Program.cs` calls, makes it obvious which databases the app talks to and which configuration keys must exist in every environment. ## Habits interviewers look for - Inject the context; never construct it with `new` inside a handler when it is registered. - Never wrap an injected context in `using`. The container owns it, and disposing it early makes later code in the same request fail with an `ObjectDisposedException` ("Cannot access a disposed context instance"). - Keep the connection string out of code and out of committed files; read it from configuration. - Leave the lifetime at its default unless you have a concrete reason; a singleton context is a defect, and code that runs outside a request uses `AddDbContextFactory` instead.

  • Why does the ASP.NET Core template follow GetConnectionString with ?? throw new InvalidOperationException(...) before calling AddDbContext?
    `GetConnectionString` returns null when the key is missing, and `AddDbContext` does not build the options at registration: they are created the first time a context is resolved. Without the throw the app starts, and the first request that touches the database fails far from the cause. Throwing in `Program.cs` turns a missing setting into a startup failure whose message names the connection string.
  • Why does AddDbContext throw an ArgumentException when the context class has only a parameterless constructor?
    If you pass an options callback, EF Core checks the context's declared constructors. A context with only a parameterless constructor could never receive the `DbContextOptions<TContext>` built from your callback, so the provider and connection string would be silently ignored. Failing at registration surfaces the mistake immediately; the fix is a constructor that takes `DbContextOptions<TContext>` and passes it to `base`.

  • AddDbContext registers the context as a singleton shared by all requests.
  • A new DbContext is created every time any class injects it in one request.
  • Wrap the injected context in a using block so the connection closes.
  • Hard-code the connection string in OnConfiguring for every environment.
  • The context must be created with new inside each Minimal API handler.
open as a page

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%

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.

open as a page

In an ASP.NET Core 10 app, when do you register AddDbContextFactory instead of AddDbContext, and which lifetimes does each registration use?

level: middleimportance: should knowfreq 45%

basics

~20 s

AddDbContext registers the context and its options Scoped, one per request. AddDbContextFactory registers a Singleton factory plus a Scoped context, for code that needs its own short-lived contexts: singletons, parallel queries or several units of work.

open as a page

In an ASP.NET Core 10 app using EF Core, what do AddDatabaseDeveloperPageExceptionFilter and UseMigrationsEndPoint do, and why are they Development-only?

level: middleimportance: should knowfreq 28%

basics

~20 s

AddDatabaseDeveloperPageExceptionFilter makes the developer exception page explain database errors caused by pending migrations; UseMigrationsEndPoint handles its Apply Migrations button by running MigrateAsync. Both are Development-only because an HTTP request changing the schema must never reach production.

open as a page

In an ASP.NET Core 10 gym-booking API, a singleton ClassScheduleCache injects BookingDbContext; why does startup fail in Development, what happens in Production, and how do you fix it?

level: seniorimportance: should knowfreq 55%

basics

~10 s

The singleton captures a scoped context. In Development WebApplicationBuilder validates scopes during Build() and throws; in Production nothing checks, so one context serves every request. Fix it with AddDbContextFactory or a scope per operation.

open as a page