Dependency Injection I learned from .NET Core

Jul 7, 2025

Back at my early web dev years, I didn't like .NET Core. It was mainly because of the new things I have never heard of. What was dependency injection? It felt like magic behind the framework.

This is my effort to explain what dependency injection is, from .NET Core. So normally, to use a class, you would instantiate one using new.

public class ReportService {
    private readonly EmailSender _emailSender;

    public ReportService() {
        _emailSender = new EmailSender(); // hard-coded dependency
    }

    public void SendReport() {
        _emailSender.Send("report.pdf");
    }
}

By using DI, you don't have to instantiate a class everytime you need to use it. They will be instantiated once at the beginning and passed along in a container.

services.AddScoped<IEmailSender, EmailSender>();
services.AddScoped<ReportService>();

// Then injected by the framework
public class ReportService {
    private readonly IEmailSender _emailSender;

    public ReportService(IEmailSender emailSender) {
        _emailSender = emailSender; // dependency is passed in (injected)
    }

    public void SendReport() {
        _emailSender.Send("report.pdf");
    }
}

This makes the code more modular, testable, flexible, and maintainable. The main case I found for this is for testing, when you need to replace the service with a testing one. Another one is easier to maintain, since you don't run around, make new classes anymore.

It makes things difficult in the beginning, because it creates a "Where is this coming from?" effect—harder to trace what's actually being used. DI often encourages interfaces, which adds complexities to code. But it's necessary to learn as this is Inversion of Control (IoC), a fundamental design principle where the control flow of a program is inverted. You don’t create dependencies yourself — they're provided to you by the framework. In this instance from .NET Core:

  • You register dependencies in a container.
  • The framework resolves and injects them.