Dependency Injection

Advanced 25 min read Lesson 9 of 10
The Restaurant Kitchen Story: Imagine a chef (Controller) who has to cook a meal. Instead of running to the market to buy vegetables and meat (creating new database connections), the restaurant manager (Dependency Injection) delivers the ingredients directly to the chef's counter. The chef just focuses on cooking!

Connecting to C#

Instead of writing var db = new AppDbContext(); inside every single API method (which is messy and hard to test), we let ASP.NET Core "inject" the database context into our class automatically.

Step 1: Register the Service (Program.cs)

You tell ASP.NET Core about your service in the Program.cs file:

// This tells the app: "When someone asks for IUserService, give them UserService"
builder.Services.AddScoped<IUserService, UserService>();

Step 2: Inject it into the Controller

You simply ask for it in the constructor of your Controller:

[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    private readonly IUserService _userService;

    // The magic happens here! ASP.NET Core passes the service automatically.
    public UsersController(IUserService userService)
    {
        _userService = userService;
    }

    [HttpGet]
    public IActionResult GetUsers()
    {
        // We use the injected service instead of creating new connections
        var users = _userService.GetAllUsers(); 
        return Ok(users);
    }
}
Why do we do this?
  • Testing: You can easily swap the real database for a fake one when writing unit tests.
  • Clean Code: Your controller doesn't need to know how to connect to the database; it just asks for the data.
  • Performance: ASP.NET Core manages the lifecycle of these objects (Scoped, Transient, Singleton) efficiently.
Test Your Knowledge - Take Quiz