DEV Community

subasri Viswanathan
subasri Viswanathan

Posted on

Dependency Injection in .NET

Dependency Injection (DI) is one of the most commonly used design patterns in .NET.
If you’re new to DI, this guide explains it in the simplest way possible.

What Is Dependency Injection?

Dependency Injection means:

A class should not create its own dependencies.
Instead, dependencies should be provided (injected) from the outside.

This is usually done through Program.cs or DependencyInjection.cs in ASP.NET Core.

Why Do We Use DI?

Here are the main advantages:

✔ Loose Coupling
Your classes do not depend on specific implementations.

✔ No Need to Create Instances Manually
You don’t use new ClassName() everywhere. The DI container manages it.

✔ Easier to Unit Test
You can replace real services with mocks.

✔ Cleaner, Maintainable Code
Follows the SOLID “Dependency Inversion Principle”.

How DI Works in C#

Using DI in .NET involves three simple steps:

  1. Register the service in Program.cs
  2. Inject the service into the constructor
  3. Use the service in the class

Service Lifetimes in DI

.NET provides three lifetimes. Choosing the correct one is important.

- Singleton
One instance for the entire application.
Created once and reused everywhere.

- Scoped
One instance per HTTP request.
Perfect for services using DbContext.

- Transient
A new instance every time it’s requested.
Best for lightweight, stateless services.

Types of Dependency Injection

✔ Constructor Injection (Most Recommended)
Dependencies are passed through the class constructor.

✔ Method Injection
Dependencies are passed directly into a method.

Example

Step 1 — Create an interface and class

public interface IAmazonS3
{
    Task<string> UploadFromStream();
}

public class AmazonS3 : IAmazonS3
{
    public async Task<string> UploadFromStream()
    {
        // Upload logic goes here
        return "Uploaded";
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2 — Inject the service into your class

public class ReportService
{
    private readonly IAmazonS3 _amazonS3;
    public ReportService(IAmazonS3 amazonS3)
    {
        _amazonS3 = amazonS3;
    }

    public async Task SaveReport()
    {
        await _amazonS3.UploadFromStream();
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3 — Register the service in DI container

In Program.cs or DependencyInjection.cs:

builder.Services.AddScoped<IAmazonS3, AmazonS3>();
Enter fullscreen mode Exit fullscreen mode

Now, whenever IAmazonS3 is needed, AmazonS3 will be automatically injected.

Summary

Dependency Injection reduces coupling and improves maintainability.
Instead of creating objects manually, .NET injects them for you.
Three lifetimes exist: Singleton, Scoped, Transient.
Constructor injection is the most commonly used pattern.
DI keeps your application clean, testable, and easy to extend.

Top comments (0)