Dependency Injection (DI) in ASP.NET Core

Posted: (EET/GMT+2)

 

Dependency Injection (or DI for short) isn't just for enterprise application, nor a buzzword; it's a simple way to make your code easier to test, extend, and reason about. In .NET, it means your classes don't create their own dependencies, but receive them instead from the "system". Put another way, if you are creating multiple class instances manually, there might be better served by DI.

ASP.NET Core has had DI support from the earliest versions. You can register your own classes as services in Startup.cs and let the framework do the wiring for you.

Let's take an example:

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IMailer, SmtpMailer>();
    services.AddMvc();
}

This says to the ASP.NET environment that whenever any class requires an IMailer interface as a constructor parameter, pass in the concrete class SmtpMailer. Here's an example implementation:

// Example service
public interface IMailer
{
    void Send(string to, string subject, string body);
}

public class SmtpMailer : IMailer
{
    public void Send(string to, string subject, string body)
    {
        // send via SMTP
    }
}

And the third code snippet shows how to get an instance inside a controller:

// Controller using DI
public class ContactController : Controller
{
    private readonly IMailer _mailer;
    public ContactController(IMailer mailer)
    {
        _mailer = mailer;
    }

    [HttpPost]
    public IActionResult SendMessage(string to, string message)
    {
        _mailer.Send(to, "Contact Form", message);
        return Ok();
    }
}

ASP.NET Core automatically resolves IMailer when it creates your controller. You can swap implementations later (for example, a mock or a SendGridMailer) without touching the rest of your code.

In short: using DI allows you to get a cleaner design, easier unit testing, and more predictable dependencies, all with a few lines of setup.