liveBook · Manning

AddDbContext<T>

As explained in .NET in Action, Second Edition

AddDbContext is an Entity Framework Core service-registration method that registers a DbContext type with a dependency injection container.

AddDbContext<T> registers a DbContext type with ASP.NET Core dependency injection, connecting database access to the application’s request pipeline. section 5.4.1

Registration provides predictable request-scoped behavior:

  • Creates one DbContext instance for each HTTP request. section 5.4.1
  • Disposes the context when the response finishes. section 5.4.1
  • Injects the same context into request-handling components such as CatalogController. section 5.4.1

Registering CatalogContext

Call builder.Services.AddDbContext<CatalogContext>() before AddControllers, then map controllers so injected CatalogContext instances are available to API actions.

How .NET in Action, Second Edition covers it

How deep it goes
Explains registration, request lifetime, disposal, and constructor injection, but stops short of internal dependency-injection mechanics.
Examples
Uses CatalogContext, CatalogController, SQLite startup configuration, database seeding, and injected query operations.
What it assumes
Assumes a DbContext subclass and an ASP.NET Core WebApplicationBuilder, while demonstrating controller injection.
What you can do after
Operate/configure ASP.NET Core services with a registered DbContext that controllers can consume safely within requests.
How it connects
Connects DbContext, dependency injection, ASP.NET Core controllers, request scope, and Entity Framework Core.

Also explained in

Compare how 2 books explain AddDbContext<T> →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.