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




















