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
