12. Dependency Injection

Dependency injection (DI) is how ASP.NET Core gives classes the objects they need instead of creating them with new. You register services in Program.cs, then ask for them in a constructor. This keeps controllers small, and makes code easy to test because a service can be replaced with a fake. Move business logic into services and keep controllers for coordination.

Key points

  • Register with AddScoped (one per request), AddSingleton (one for the whole app) or AddTransient (new every time).
  • Program against an interface such as IStudentService.
  • Constructor injection is the standard way to receive services.

Example: Service, registration and use

Service layer
// Interface and implementation
public interface IStudentService
{
    List<Student> GetAll();
}

public class StudentService : IStudentService
{
    public List<Student> GetAll() => new() { new Student { Name = "Ana" } };
}

// Program.cs
builder.Services.AddScoped<IStudentService, StudentService>();

// Controller
public class StudentsController : Controller
{
    private readonly IStudentService _service;

    public StudentsController(IStudentService service)
    {
        _service = service;
    }

    public IActionResult Index() => View(_service.GetAll());
}
Show explanation

The framework creates StudentService and passes it to the controller. To change how students are loaded you only change the service.