Introduction
When I started working on real-world ASP.NET Core projects, one mistake I repeatedly made was creating objects directly inside controllers. At first, this felt simple and fast. But as the application grew, the code became tightly coupled, difficult to test, and painful to maintain.
That’s when I truly understood the importance of Dependency Injection (DI).
ASP.NET Core provides built-in support for DI, and once you start using it correctly, it completely changes how you structure applications. In this article, I’ll explain Dependency Injection from a practical developer’s perspective, using a simple logging example that I’ve personally used while debugging APIs and tracking requests.
What is Dependency Injection (In Simple Terms)
Dependency Injection is a design pattern where a class does not create the objects it depends on.
Instead, those objects are provided externally.
Without Dependency Injection
public class HomeController : ControllerBase
{
private ConsoleLoggerService _logger = new ConsoleLoggerService();
}
Problems I faced with this approach:
Controller is tightly coupled to one implementation
Hard to replace logger later
Unit testing becomes difficult
With Dependency Injection
public class HomeController : ControllerBase
{
private readonly ILoggerService _logger;
public HomeController(ILoggerService logger)
{
_logger = logger;
}
}
Now:
Controller depends on an interface
Implementation can change anytime
Code becomes clean and testable
Real-Time Scenario: Logging in an ASP.NET Core Application
In almost every project I’ve worked on, logging is mandatory:
API request tracking
Error debugging
Auditing user actions
Instead of hardcoding logging logic everywhere, DI allows us to centralize and inject it.
Step 1: Define a Logging Interface
I always start with an interface. This gives flexibility from day one.
public interface ILoggerService
{
void Log(string message);
}
Why interface first?
Allows multiple implementations
Makes unit testing easier
Follows clean architecture principles
Step 2: Implement the Service
For this demo, I’m using a simple console logger.
public class ConsoleLoggerService : ILoggerService
{
public void Log(string message)
{
Console.WriteLine($"[LOG] {message}");
}
}

Join the conversation! Your thoughts help the community grow.