7 Using dependency injection to manage services

 

This chapter covers

  • Understanding the role of dependency injection
  • Examining dependency injection in ASP.NET Core
  • Creating and using your own services
  • Managing service lifetime

Dependency injection (DI) is a software engineering technique that is included as a feature in many web frameworks these days. Its raison d'être is to enable loose coupling between software components, resulting in code that is less brittle, more adaptable to change, easier to maintain, and easier to test. If you have worked with dependency injection before, all of this will feel familiar to you. If dependency injection is a new concept to you, this chapter will do its best to explain what it is and why you should care.

DI is at the heart of ASP.NET Core. The entire framework uses the built-in DI feature to manage its own dependencies or “services.” Services are globally registered within a container when the application starts up and then provided by the container when needed by consumers. We have already encountered the main entry point to the service container when we looked at Program.cs in chapter 2.  It is accessed via the Services property of the WebApplicationBuilder. You will recall that services that comprise the Razor Pages framework are registered with the container via the AddRazorPages method:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();

7.1 The reason for dependency injection

 
 

7.1.1 Single responsibility principle

 
 
 

7.1.2 Loose coupling

 
 

7.1.3 Dependency inversion

 
 
 

7.1.4 Dependency injection

 

7.2 Inversion of control containers

 
 

7.2.1 Service registration

 
 
 
 

7.2.2 Service lifetimes

 
 

7.2.3 Captive dependencies

 
 
 

7.2.4 Other service registration options

 
 
 
 

7.2.5 Registering multiple implementations

 
 
 
 

7.3 Other ways of accessing registered services

 
 
 

7.3.1 View injection

 
 
 

7.3.2 Method injection

 
 
 
 

7.3.3 Directly from the service container with GetService and GetRequiredService

 
 
 
 

7.4 Summary

 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest