Dependency Injection in ASP.NET Core
In this lesson, we will learn how to implement dependency injection in ASP.NET Core.
.NET Core makes dependency injection available to all applications that use the Host pattern. A host is a software environment where software threads called hosted services run and share common resources that include:
- Application start and shutdown. When the application starts all hosted services are launched, and when the operating system, or a hosted service, or the main that created the Host requires a shutdown, all hosted services are notified. This ensures clean shutdown instead of the process aborting.
- Application configuration and file services. The Host can supply configuration information to all hosted services from several sources such as JSON and XML files, and environment variables. We will describe the ASP.NET Core configuration in a dedicated chapter. File services include the definition of some default folders and the virtualization of the file system through interfaces that make file access independent of their actual physical location. ASP.NET Core internally uses virtualization to retrieve compiled views and static content like CSS and JavaScript.
- Dependency injection. All hosted services access the same dependency injection container that is defined once when the Host is defined. Hosted services themselves are added to the dependency injection container.
The code below defines an ASP.NET Core Host:
Get hands-on with 1400+ tech skills courses.