Dependency Injection in ASP.NET Core explained with real examples using services and C# illustration

Dependency Injection in ASP.NET Core: Explained with Real Examples (2026 Guide)

What is Dependency Injection?

Why Use Dependency Injection?

1. Promotes Loose Coupling

2. Improves Testability

3. Better Maintainability and Scalability

4. Reusable Services

5. Built-In Support in ASP.NET Core

Different Types of Dependency Injection?

1. Constructor Injection

public class ProductController
{
    private readonly IProductService _productService;

    public ProductController(IProductService productService)
    {
        _productService = productService;
    }
}

2. Property Injection (Not Common in ASP.NET Core)

public class ProductController
{
    public IProductService ProductService { get; set; }
}

3. Method Injection (Limited Use)

public class ProductController
{
    public void GetProducts(IProductService productService)
    {
        var products = productService.GetProducts();
    }
}

Implementing Dependency Injection with a Real Example in .NET Core

Step 1: Create a Service Interface

public interface IProductService 
{ 
   IEnumerable<string> GetProducts(); 
}

Step 2: Create the Service Class

public class ProductService : IProductService 
{ 
    public IEnumerable<string> GetProducts() 
    { 
        return new List<string> { "Laptop", "Mobile", "Tablet" }; 
    } 
}

Step 3: Register the Service in the DI Container

builder.Services.AddScoped<IProductService, ProductService>();

Step 4: Use the Service in a Controller

[ApiController] 
[Route("api/[controller]")] 
public class ProductController : ControllerBase 
{ 
  private readonly IProductService _productService; 
  public ProductController(IProductService productService) 
  {
      _productService = productService; 
  }

  [HttpGet] 
  public IActionResult GetProducts() 
  { 
    var products = _productService.GetProducts(); return Ok(products); 
  } 
}

How It Works

Service Lifetimes in Dependency Injection

1. Singleton

builder.Services.AddSingleton<IProductService, ProductService>();

2. Scoped

builder.Services.AddScoped<IProductService, ProductService>();

3. Transient

builder.Services.AddTransient<IProductService, ProductService>();

Quick Summary Table

Tip:

Advantages of Using Dependency Injection in .NET Core

1. Loose Coupling

2. Easier Testing

3. Better Maintainability

4. Reusable Services

5. Follows SOLID Principles

Best Practices for Using Dependency Injection in .NET Core

Use Interfaces for Services

Choose the Right Service Lifetime

Keep Classes Simple

Register Services in One Place

Avoid Creating Services Manually

Conclusion

Related Articles

🚀 Subscribe for Tech Updates

📧

👤

We respect your privacy. Unsubscribe anytime.

Leave a Comment

Your email address will not be published. Required fields are marked *