liveBook · Manning

Dependency inversion

As explained in ASP.NET Core in Action, 3e

The dependency inversion principle is a design principle in which high-level modules depend on abstractions rather than low-level implementation details.

Dependency inversion keeps high-level code focused on its work by depending on abstractions instead of low-level implementation details. Dependency injection is a related technique, but the two concepts are not identical. section 8.1

In an ASP.NET Core application, a registration handler can require an EmailSender without constructing it or knowing how its dependencies are created. The container supplies the implementation, reducing wiring in application code and helping control complexity as the application grows. section 8.1

The practical contrast is:

  • Construct dependencies directly when the application is simple and the extra wiring is not warranted. section 8.1
  • Declare required services such as EmailSender and let the container create them when dependencies become more complex. section 8.1
Listing 8.4 Sending an email using DI to inject dependencies
string RegisterUser(string username, EmailSender emailSender)   #1
{
    emailSender.SendEmail(username);                            #2
    return $"Email sent to {username}!";                        #2
}

Compare the small registration handler that receives EmailSender with the manual construction of MessageFactory, NetworkClient, and email settings. section 8.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Defines the principle, distinguishes it from dependency injection, and demonstrates container-provided services without exploring container internals.
Examples
Demonstrates user registration, EmailSender, MessageFactory, NetworkClient, and email server settings.
What it assumes
Assumes basic object-oriented programming concepts and treats direct construction as the starting point before introducing DI.
What you can do after
Apply it via ASP.NET Core dependency injection by declaring required services instead of constructing their dependency graph manually.
How it connects
Connects dependency inversion with SOLID, dependency injection, and inversion of control.

Also explained in

Compare how 6 books explain dependency inversion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.