liveBook · Manning

Dependency injection

As explained in Building Web APIs with ASP.NET Core

Dependency injection is a software design pattern in which a component receives its required dependencies from an external provider rather than constructing them itself.

Dependency injection (DI) lets a component receive required dependencies from an external provider instead of constructing them itself. In ASP.NET Core, this supports inversion of control and encourages modular, testable, maintainable applications built from reusable services. section 1.2.1

ASP.NET Core organizes the process into three practical stages:

  • Implement each service behind an interface or base class; the implementation may come from the framework, the application, or a third party. section 1.2.1
  • Register and configure services in the built-in IServiceProvider service container, using Program.cs as the application entry point. section 1.2.1
  • Inject registered services where components need them, commonly through a controller constructor, then retain the instance for the controller’s lifecycle. section 5.2 section 5.7

Injecting a database context

A BoardGamesController can receive an ApplicationDbContext in its constructor and store it in a private field. Its Get method then uses that context to build an IQueryable query and execute it with ToArray(), replacing manually generated board-game data with records retrieved from the database. section 5.2

Listing 5.1 BoardGameController.cs file
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyBGList.DTO;
using MyBGList.Models;
 
namespace MyBGList.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class BoardGamesController : ControllerBase
    {
private readonly ApplicationDbContext _context;  #1
 
        private readonly ILogger<BoardGamesController> _logger;
 
        public BoardGamesController(
ApplicationDbContext context,         #2
            ILogger<BoardGamesController> logger
        )
        {
_context = context;#2
            _logger = logger;
        }
 
        [HttpGet(Name = "GetBoardGames")]
        [ResponseCache(Location = ResponseCacheLocation.Any, Duration = 60)]
        public RestDTO<BoardGame[]> Get()
        {
var query =  _context.BoardGames;            #3
 
            return new RestDTO<BoardGame[]>()
            {
                Data = query.ToArray(),                  #4
                Links = new List<LinkDTO> {
                    new LinkDTO(
                        Url.Action(null, "BoardGames", 
                            null, Request.Scheme)!,
                        "self",
                        "GET"),
                }
            };
        }
    }
}

The annotated controller listing shows the injected ApplicationDbContext field, constructor parameter, assignment, and query usage in sequence. section 5.2

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Explains implementation, registration, and constructor injection, then demonstrates database querying without descending into container internals.
Examples
Uses Program.cs registration and a BoardGamesController receiving ApplicationDbContext to replace dummy data with database results.
What it assumes
Assumes familiarity with ASP.NET Core controllers and introduces services as application dependencies before applying injection.
What you can do after
Apply it via ASP.NET Core constructor injection to access ApplicationDbContext from controller action methods.
How it connects
Connects dependency injection with inversion of control, services, middleware, service containers, controllers, and LINQ queries.

Also explained in

Compare how 21 books explain dependency injection →

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.