liveBook · Manning

Service type

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

A service type is the class or interface that a dependency injection container uses as the requested dependency contract.

A service type is the class or interface that a dependency injection container expects when an application requests a dependency. It defines the contract to match, not necessarily the class the container creates. section 9.1

A service registration describes three related choices:

  • Service type — the requested dependency, often an interface such as IEmailSender, but sometimes a concrete class such as NetworkClient. section 9.1
  • Implementation type — the concrete class the container creates to satisfy that request, such as EmailSender. section 9.1
  • Lifetime — how long the container reuses the resulting instance, such as transient, scoped, or singleton. section 9.1 section 9.6

Registering a service type

builder.Services.AddScoped<IEmailSender, EmailSender>(); registers IEmailSender as the requested service type and EmailSender as its implementation. An endpoint can then request IEmailSender, while the container supplies EmailSender and its registered dependencies. section 9.1

Listing 9.3 Registering services with the DI container
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
 
builder.Services.AddScoped<IEmailSender, EmailSender>();   #1
builder.Services.AddScoped<NetworkClient>();               #2
builder.Services.AddSingleton<MessageFactory>();           #3
 
WebApplication app = builder.Build();
 
app.MapGet("/register/{username}", RegisterUser);
 
app.Run();
 
string RegisterUser(string username, IEmailSender emailSender)
{
    emailSender.SendEmail(username);
    return $"Email sent to {username}!";
}
#1 Whenever you require an IEmailSender, use EmailSender.
#2 Whenever you require a NetworkClient, use NetworkClient.
#3 Whenever you require a MessageFactory, use MessageFactory.

Inspect the registration and endpoint together to see how a requested service type is mapped to an implementation. section 9.1

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

How deep it goes
Defines service, implementation, and lifetime roles, then stops short of detailed lifetime treatment.
Examples
Uses IEmailSender, EmailSender, NetworkClient, MessageFactory, and an endpoint that requests IEmailSender.
What it assumes
Assumes dependency injection basics while teaching the distinction between concrete, interface, and abstract types.
What you can do after
Apply it via IServiceCollection by registering a requested service type with an implementation and lifetime.
How it connects
Connects dependency injection with implementation type, service lifetime, constructor injection, and multiple service registrations.

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.