liveBook · Manning

Bean scope

As explained in Building Web APIs with ASP.NET Core

A scoped service is a dependency-injected service instance whose lifetime is limited to a single scope, typically one HTTP request in ASP.NET Core.

A scoped service lives for one unit of work. In the board-game API, ApplicationDbContext is registered with ASP.NET Core’s service provider so a batch operation can use the same context before it is disposed. section 4.3.4

Configure the scoped database service in Program.cs:

  • Register ApplicationDbContext with AddDbContext. section 4.3.4
  • Configure SQL Server using the DefaultConnection connection string. section 4.3.4
  • Use SaveChanges after the batch operation so EF Core detects and persists the changes. section 4.3.4
  • Keep credentials out of committed source by using ignored development settings, environment variables, or Secret Manager. section 4.3.4
builder.Services.AddDbContext<ApplicationDbContext>(options =>
   options.UseSqlServer(
       builder.Configuration.GetConnectionString("DefaultConnection"))
   );

The registration connects the scoped ApplicationDbContext to SQL Server and retrieves the DefaultConnection value from configuration. section 4.3.4

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Explains scoped registration, SaveChanges timing, change detection, persistence, and disposal before addressing connection-string security.
Examples
Uses ApplicationDbContext in Program.cs with a SQL Server DefaultConnection for the MyBGList API.
What you can do after
Operate/configure ApplicationDbContext as a scoped service and protect its connection string with development settings or environment variables.
How it connects
Connects bean scope with dependency injection, DbContext, unit of work, SaveChanges, SQL Server, and configuration.

Also explained in

Compare how 3 books explain bean scope →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.