Introduction
When building applications using ASP.NET Core, we often create objects inside classes.
Example:
ProductService service = new ProductService();But this is not a good practice in large applications.
Why?
Because:
Code becomes tightly coupled
Hard to test
Hard to maintain
Difficult to scale
To solve this problem, ASP.NET Core uses:
Dependency Injection (DI)
In this article, we will learn:
What is Dependency Injection?
Why do we use it?
How it works?
Step-by-step example
Output explanation
Everything in simple words.
What is Dependency Injection?
Dependency Injection means:
Instead of creating an object inside a class, we provide (inject) the object from outside.
Simple meaning:
“Don’t create dependency. Receive dependency.”
Why Use Dependency Injection?
Without DI:
Classes depend on specific implementations
Difficult to change code
Hard to write unit tests
With DI:
Loose coupling
Easy testing
Clean code
Better maintainability
Real-Life Example
Think like this:
A Car needs an Engine
Instead of building the engine inside the car
The engine is provided from outside
That is Dependency Injection.
Step-by-Step Example in ASP.NET Core
Step 1 – Create Interface
Create a folder: Services
Add Interface:
public interface IMessageService
{
string GetMessage();
}
Step 2 – Create Service Class
public class MessageService : IMessageService
{
public string GetMessage()
{
return "Hello from Dependency Injection!";
}
}
Step 3 – Register Service in Program.cs
Open Program.cs:
builder.Services.AddScoped<IMessageService, MessageService>();
This tells ASP.NET Core:
Whenever IMessageService is required
Provide MessageService object
Step 4 – Use in Controller
using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
private readonly IMessageService _messageService;
public HomeController(IMessageService messageService)
{
_messageService = messageService;
}
public IActionResult Index()
{
var message = _messageService.GetMessage();
ViewBag.Message = message;
return View();
}
}
Marcin Szolke ScholkePosted Feb 26, 2026, 5:15 PM
Perfect - i like this solution old projects without Dependency Injection - Desktop, Web - IT WAS TERRIBLE :)