Lesson 26 of 40 Architecture Intermediate 40 min

Dependency Injection

Learn how Dependency Injection (DI) works in ASP.NET Core and why it is a key concept for building clean, flexible, and maintainable applications. DI is used throughout ASP.NET Core and is one of its most powerful features.

Part 1: What Is Dependency Injection?

Dependency Injection is a design pattern used to supply an object with the dependencies it needs, rather than having the object create those dependencies itself.

In simple terms, instead of a class creating its own resources, those resources are provided to it from outside.

Part 2: Why Dependency Injection Matters

Without Dependency Injection, classes can become tightly coupled, meaning they depend heavily on specific implementations.

Dependency Injection improves your application by:

This makes large applications much easier to manage.

Part 3: A Simple Example Without DI

Consider a controller that directly creates a service:

public class StudentController
{
  private StudentService _service = new StudentService();
}

This approach tightly couples the controller to a specific implementation, making it harder to change or test later.

Part 4: Using Dependency Injection

With Dependency Injection, the service is provided to the controller instead of being created inside it.

private readonly StudentService _service;

public StudentController(StudentService service)
{
  _service = service;
}

This makes the controller more flexible and easier to maintain.

Part 5: Registering Services

Before a service can be injected, it must be registered in the application. This is usually done in Program.cs.

builder.Services.AddScoped<StudentService>();

This tells ASP.NET Core how to create and manage the service.

Part 6: Service Lifetimes

ASP.NET Core supports different lifetimes for services:

Lifetime Description
Transient A new instance is created each time it is requested
Scoped One instance per request
Singleton A single instance for the entire application

Choosing the correct lifetime is important for performance and behavior.

Part 7: Dependency Injection in the Student Project

In your Student CRUD application, Dependency Injection is already used when injecting DbContext into controllers.

You can also use DI for:

This helps keep your code organized and scalable.

Part 8: Best Practices

Following these practices will improve code quality and maintainability.

Summary

Dependency Injection is a fundamental concept in ASP.NET Core. It allows your application to remain flexible, testable, and easy to maintain. Once mastered, DI becomes a powerful tool for building clean and scalable systems.

VISUAL STUDIO 2026 MADE EASY
Recommended Book

VISUAL STUDIO 2026 MADE EASY

Build real applications with C#, VB.NET, Python, JavaScript, C++, and .NET 10. A practical companion for mastering Visual Studio 2026 step by step.