Day 14 – Dependency Injection in ASP.NET Core Explained Simply


Introduction

Dependency Injection (DI) is a fundamental design pattern that promotes loose coupling and testability in applications. In ASP.NET Core, DI is built-in and enables developers to inject services, repositories, and configurations into controllers and other components efficiently.

At CuriosityTech.in, we guide FullStack .NET learners to master DI with practical examples, ensuring scalable and maintainable applications.


1. What is Dependency Injection?

Dependency Injection is a technique to provide dependencies (services or objects) to a class instead of letting the class create them itself.

Example without DI:

public class CourseController

{

    private CourseService _courseService = new CourseService(); // tightly coupled

}

Example with DI:

public class CourseController

{

    private readonly ICourseService _courseService;

    public CourseController(ICourseService courseService)

    {

        _courseService = courseService; // injected

    }

}

Benefits:

  • Promotes loose coupling
  • Makes unit testing easier
  • Improves maintainability

2. Registering Services in ASP.NET Core

ASP.NET Core provides three lifetimes for services:

LifetimeDescriptionExample
SingletonSingle instance for entire appbuilder.Services.AddSingleton<ICacheService, CacheService>();
ScopedSingle instance per requestbuilder.Services.AddScoped<ICourseService, CourseService>();
TransientNew instance every timebuilder.Services.AddTransient<INotificationService, EmailService>();

Registering in Program.cs:

builder.Services.AddScoped<ICourseService, CourseService>();


3. Injecting Services into Controllers

[ApiController]

[Route(“api/[controller]”)]

public class CourseController : ControllerBase

{

    private readonly ICourseService _courseService;

    public CourseController(ICourseService courseService)

    {

        _courseService = courseService;

    }

    [HttpGet]

    public IActionResult GetAllCourses()

    {

        var courses = _courseService.GetCourses();

        return Ok(courses);

    }

}

Explanation:

  • CourseService is injected via the constructor
  • Controller does not create the service, promoting loose coupling

4. Real-World Project: CuriosityTech Course Portal

Scenario: Build a full-featured course portal with services:

  • CourseService → Handles course logic
  • StudentService → Handles student management
  • EmailService → Sends notifications for enrollments

Flow Diagram:


5. Using Dependency Injection for Configuration

ASP.NET Core allows injecting configuration values:

public class EmailService : IEmailService

{

    private readonly IConfiguration _config;

    public EmailService(IConfiguration config)

    {

        _config = config;

    }

    public void SendEmail(string to, string subject)

    {

        var smtpServer = _config[“SMTP:Server”];

        // send email logic

    }

}

Benefit: Decouples configuration from implementation and makes it flexible.


6. Best Practices

  • Use interfaces for all services to enable swapping implementations
  • Keep controllers thin; business logic should be in services
  • Avoid Service Locator pattern; prefer constructor injection
  • Use Scoped services for database contexts (EF Core DbContext)
  • Register services in Program.cs centrally for better management

7. CuriosityTech.in Mentorship Insights

  • Hands-on guidance to implement DI in real projects
  • Stepwise approach: services → controllers → repositories
  • Prepare learners for industry-standard FullStack architecture

Conclusion

Dependency Injection is a core principle for scalable .NET applications. By using DI in ASP.NET Core, developers can achieve loose coupling, maintainable code, and easy testing. With CuriosityTech.in mentorship, learners can implement DI in real-world course portals or enterprise apps, preparing for professional FullStack development.

The next step is Day 15 – Error Handling & Logging Best Practices in .NET Projects, focusing on building robust, maintainable, and debuggable applications.


Leave a Comment

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