C#  

Dependency Injection in C#

Introduction

In this article , we will see what is dependency injection and how to use in a real practical example.

Dependency Injection (DI) is a programming concept where an object gets what it needs from outside instead of creating it itself.

Simple way to think about it:

Consider the process of making tea :

Without DI: You go and gather water, milk, tea leaves yourself.

With DI: Someone hands you all the ingredients—you just make the tea.

In programming terms:

A class often needs other classes (dependencies) to work.

Instead of creating those dependencies inside the class, you inject (provide) them from outside.

let's see with the real world example :

Without Dependency Injection (DI) :


class EmailService
{
    public void Send(string message)
    {
        Console.WriteLine("Email sent: " + message);
    }
}

class Notification
{
    private EmailService _emailService = new EmailService(); 

    public void Notify(string message)
    {
        _emailService.Send(message);
    }
}

Problem in Example :

  • Tight Coupling Without Dependency Injection

  • You can only send emails

  • Hard to switch to SMS later

  • Hard to test

With Dependency Injection (DI)

Step 1: Create Interface (/Services/INotificationService.cs)

public interface INotificationService
{
    void Send(string message);
}

Step 2: Create Multiple Implementations

(/Services/EmailService.cs)


public class EmailService : INotificationService
{
    public void Send(string message)
    {
        Console.WriteLine("Email sent: " + message);
    }
}

(/Services/SmsService.cs) :


public class SmsService : INotificationService
{
    public void Send(string message)
    {
        Console.WriteLine("SMS sent: " + message);
    }
}

Step 3: Inject into Class (/Models/Notification.cs)


public class Notification
{
    private readonly INotificationService _service;

    public Notification(INotificationService service)
    {
        _service = service;
    }

    public void Notify(string message)
    {
        _service.Send(message);
    }
}

Dependency Injection in ASP.NET Core

Step 4: Register Service (Program.cs) :

builder.Services.AddScoped<INotificationService, EmailService>();

Step 5 : Use in controller (/Controllers/HomeController.cs)


public class HomeController : Controller
{
    private readonly INotificationService _service;

    public HomeController(INotificationService service)
    {
        _service = service;
    }

    public IActionResult Index()
    {
        _service.Send("Welcome!");
        return View();
    }
}

Why This Matters in Real Life

 - Easily switch Email → SMS → WhatsApp

Conclusion

In this article , we explored what is dependency injection with real world example and use in real project.

Hope this helps you!