liveBook · Manning

AddDbContext<T>

As explained in ASP.NET Core in Action, 3e

AddDbContext<T> is an ASP.NET Core dependency-injection extension method that registers an Entity Framework Core database context type and configures its provider and options.

AddDbContext<T> registers an Entity Framework Core DbContext with ASP.NET Core dependency injection. Its configuration selects a database provider and supplies the connection string used at runtime. section 12.2.3

Listing 12.4 Registering a DbContext with the DI container
using Microsoft.EntityFrameworkCore;
WebApplicationBuillder builder = WebApplication.CreateBuilder(args);
var connString = builder.Configuration                  #1
        .GetConnectionString("DefaultConnection");      #1
 
Builder.Services.AddDbContext<AppDbContext>(            #2
        options => options.UseSqlite(connString));      #3
 
WebApplication app = builder.Build();
app.Run();

Register AppDbContext in Program.cs by reading DefaultConnection from configuration and passing it to UseSqlite. section 12.2.3

A typical registration:

  • Load the environment-specific connection string from configuration. section 12.2.3
  • Call AddDbContext<AppDbContext> with an options configuration function. section 12.2.3
  • Select the provider with UseSqlite or the appropriate Use* method for another database. section 12.2.3
  • Use the resulting scoped DbContext through dependency injection; migrations and database updates remain separate operations. section 12.2.3 section 12.6

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains the options configuration function, provider selection, connection loading, and scoped lifetime without detailing provider internals.
Examples
Uses AppDbContext, DefaultConnection, Program.cs, UseSqlite, and the Microsoft.EntityFrameworkCore.SQLite package.
What you can do after
Operate/configure an ASP.NET Core application so injected DbContext instances can interact with EF Core and its database.
How it connects
Connects DbContext, dependency injection, EF Core providers, connection strings, configuration, and migrations.

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 ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.