14 Using dependency injection

 

This chapter covers

  • Understanding how dependency injection allows components to access shared services
  • Configuring services lifecycles to control when services are instantiated
  • Understanding how to define and access services using dependency injection

Services are objects that are shared between middleware components and endpoints. There are no restrictions on the features that services can provide, but they are usually used for tasks that are needed in multiple parts of the application, such as logging or database access.

The ASP.NET Core dependency injection feature is used to create and consume services. This topic causes confusion and can be difficult to understand. In this chapter, I describe the problems that dependency injection solves and explain how dependency injection is supported by the ASP.NET Core platform. Table 14.1 puts dependency injection in context.

14.1 Preparing for this chapter

14.1.1 Creating a middleware component and an endpoint

14.1.2 Configuring the request pipeline

14.2 Understanding service location and tight coupling

14.2.1 Understanding the service location problem

14.2.2 Understanding the tightly coupled components problem

14.3 Using dependency injection

14.3.1 Using a Service with a Constructor Dependency

14.3.2 Getting services from the HttpContext object

14.4 Using Service Lifecycles

14.4.1 Creating transient services

14.4.2 Avoiding the transient service reuse pitfall

14.4.3 Using scoped services

14.5 Other dependency injection features

14.5.1 Creating dependency chains

14.5.2 Accessing services in the Program.cs file

14.5.3 Using service factory functions

14.5.4 Creating services with multiple implementations

14.5.5 Using unbound types in services

Summary