liveBook · Manning

Constructor injection

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

Constructor injection is a dependency injection technique in which required dependencies are supplied through an object's constructor.

Constructor injection supplies a class's required dependencies through its constructor. A dependency-injection container inspects that constructor and creates or provides the required objects, so application code can use a service without constructing its dependency graph manually. section 8.1

Injecting an email sender

An email service can declare its collaborators directly: EmailSender(MessageFactory factory, NetworkClient client). The endpoint then declares EmailSender as a parameter, calls SendEmail, and leaves object creation to the container. This avoids manually nesting new expressions for MessageFactory, NetworkClient, and EmailServerSettings. 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 injected endpoint signature with manual construction in the related listings. section 8.1

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

How deep it goes
Explains constructor inspection and contrasts injection with manually creating a nested dependency graph, without detailing container configuration.
Examples
Demonstrates EmailSender receiving MessageFactory and NetworkClient, then being supplied to a RegisterUser endpoint.
What you can do after
Apply it through ASP.NET Core's built-in DI container and endpoint handler injection.
How it connects
Connects constructor injection with dependency injection, DI containers, interfaces, and loose coupling.

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.