Dependency Injection

Decouple your code for testability and flexibility

Posted by Rodrigo Castro on February 9, 2025

Dependency Injection (DI) is a technique for achieving loose coupling and easier testing.

🤝 What is DI?

  • Instead of creating dependencies (classes/services) yourself, you “inject” them (usually via constructor parameters).

🏗️ Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public interface IMessageSender
{
    void Send(string message);
}

public class EmailSender : IMessageSender
{
    public void Send(string message) => Console.WriteLine($"Email: {message}");
}

public class NotificationService
{
    private readonly IMessageSender _sender;
    public NotificationService(IMessageSender sender) => _sender = sender;
    public void Notify(string message) => _sender.Send(message);
}

🛠️ Registering Services in .NET Core

1
2
services.AddTransient<IMessageSender, EmailSender>();
services.AddTransient<NotificationService>();
  • Now, the DI framework will create and inject dependencies automatically.

🧪 Testing

  • Easily swap out real implementations for mocks/fakes in tests.

Next: Docker image building!