You are currently viewing Understanding Dependency Injection in ASP.NET Core Without the Jargon

Understanding Dependency Injection in ASP.NET Core Without the Jargon

Dependency Injection was one of those programming terms that sounded much more intimidating than the idea actually was.

The name doesn’t help.

Dependency. Injection.

It sounds like either an advanced architecture technique or something that requires medical supervision.

But once I stopped focusing on the terminology, the idea became surprisingly simple.

A class sometimes needs another object in order to do its job.

Instead of having the class create that object itself, we give it the object it needs.

That’s dependency injection.

What Is a Dependency?

Suppose I have an AccountsController.

Its job might include creating and retrieving financial accounts.

But I don’t necessarily want the Controller itself to contain all of the account-processing logic.

Instead, it can use an account service.

public class AccountsController : Controller
{
    private readonly IAccountService _accountService;

    public AccountsController(IAccountService accountService)
    {
        _accountService = accountService;
    }
}

IAccountService is a dependency of AccountsController.

The Controller needs it in order to do its job.

The Controller Doesn’t Build Its Own Service

Without dependency injection, I could do something like this:

public class AccountsController : Controller
{
    private readonly AccountService _accountService;

    public AccountsController()
    {
        _accountService = new AccountService();
    }
}

At first glance, this seems fine.

The Controller needs an AccountService, so it creates one.

Problem solved.

Except now my Controller is tightly connected to that specific implementation.

AccountsController
       ↓
AccountService

The Controller decides:

  • Which service to use
  • How the service is created
  • What dependencies the service needs

The Controller is taking on responsibilities that don’t really belong to it.

Dependency Injection Flips That Around

Instead, I can say:

public AccountsController(
    IAccountService accountService)
{
    _accountService = accountService;
}

Now the Controller essentially says:

I need something that behaves like an IAccountService. Give me one.

It doesn’t need to know where that object came from.

That is the part I like about dependency injection.

The class declares what it needs.

Something else handles creating it.

ASP.NET Core Has a Container

ASP.NET Core has a built-in dependency injection container.

I register services when the application starts.

For example:

builder.Services.AddScoped
    <IAccountService, AccountService>();

I’m basically telling ASP.NET Core:

Whenever something asks for an IAccountService, use AccountService.

Then my Controller can request it:

public AccountsController(
    IAccountService accountService)
{
    _accountService = accountService;
}

ASP.NET Core sees that constructor and supplies the object automatically.

The flow looks something like this:

SERVICE REGISTRATION

IAccountService
      ↓
AccountService
      ↓
DI CONTAINER

Then...

AccountsController
      ↑
IAccountService supplied automatically

That’s the “injection.”

The dependency is being supplied to the class.

A Simple Real-World Comparison

Imagine hiring someone to work at a restaurant.

Their job description says:

This chef requires an oven.

There are two approaches.

Without Dependency Injection

The chef arrives at work, leaves the restaurant, buys an oven, installs it, wires the electricity, and then finally starts cooking.

That’s a lot of responsibility for the chef.

With Dependency Injection

The restaurant provides an oven.

The chef simply uses it.

Chef needs Oven
Restaurant provides Oven
Chef cooks

The chef depends on the oven.

But the chef doesn’t need to manufacture one.

That’s roughly how I think about dependency injection.

Why Interfaces Are Useful

I frequently see dependency injection combined with interfaces:

public interface IAccountService
{
    Task CreateAsync(
        CreateAccountViewModel model);
}

Then:

public class AccountService : IAccountService
{
    public async Task CreateAsync(
        CreateAccountViewModel model)
    {
        // implementation
    }
}

The Controller depends on:

IAccountService

instead of:

AccountService

That gives me more flexibility.

I could later create another implementation:

public class CachedAccountService 
    : IAccountService
{
}

or a fake implementation for testing.

The Controller doesn’t necessarily have to change.

It only cares that the object follows the contract defined by IAccountService.

Dependency Injection Makes Testing Easier

This is where dependency injection started connecting to other things I was learning.

Suppose my Controller accepts:

IAccountService

During normal application execution, ASP.NET Core might inject:

AccountService

During a unit test, I could instead inject a mock:

var mockService =
    new Mock<IAccountService>();

var controller =
    new AccountsController(
        mockService.Object);

Now my test doesn’t need the real service.

That’s incredibly useful because I can isolate the Controller and test only its behavior.

So:

DEPENDENCY INJECTION
        ↓
LOOSE COUPLING
        ↓
EASIER TESTING

These concepts aren’t separate topics anymore.

They start connecting.

What Are AddScoped, AddTransient, and AddSingleton?

When registering dependencies in ASP.NET Core, I commonly see three methods:

AddTransient()
AddScoped()
AddSingleton()

These control how long an instance lives.

Transient

builder.Services.AddTransient
    <IEmailService, EmailService>();

A new instance is created whenever one is requested.

Think:

Give me a fresh one.

Scoped

builder.Services.AddScoped
    <IAccountService, AccountService>();

In a typical ASP.NET Core web application, one instance is generally used for the lifetime of a single HTTP request.

Think:

One per web request.

This is commonly used with services that work with Entity Framework Core’s DbContext.

Singleton

builder.Services.AddSingleton
    <IApplicationClock, ApplicationClock>();

One instance is created and reused throughout the application’s lifetime.

Think:

One for the whole application.

Because it lives so long, I have to be more careful about what state a Singleton keeps and what other dependencies it uses.

Entity Framework Core Uses Dependency Injection Too

Even the database context can be registered with the DI container.

builder.Services.AddDbContext<ApplicationDbContext>(
    options =>
        options.UseSqlServer(
            builder.Configuration
                .GetConnectionString(
                    "DefaultConnection")));

Then a service can request the context:

public class AccountService
{
    private readonly ApplicationDbContext _context;

    public AccountService(
        ApplicationDbContext context)
    {
        _context = context;
    }
}

Again, the service doesn’t construct the database context itself.

It asks for what it needs.

ASP.NET Core supplies it.

The Pattern I See Everywhere Now

Once I understood constructor injection, I started noticing the same pattern everywhere.

public Something(
    IDependency dependency)
{
    _dependency = dependency;
}

Which basically means:

My class needs this thing.

Please give it to me.

That’s considerably less frightening than the phrase “Dependency Injection.”

How I Think About It Now

My simplest explanation is:

Dependency Injection means a class receives the things it needs instead of being responsible for creating them itself.

And ASP.NET Core gives us a container that helps manage those objects.

That leads to code that is generally easier to:

  • Test
  • Replace
  • Extend
  • Maintain
  • Understand

More importantly, dependency injection taught me another lesson about application architecture.

A good class shouldn’t try to do everything.

It should know what its responsibility is, declare what it needs, and let other parts of the application handle theirs.

Leave a Reply