...

/

Dependency Injection in ASP.NET Core

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:

Press + to interact
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}

Host definition uses the build pattern, that is, all Host features are defined in a declarative way using a builder object. These definitions are then used to build the actual host, by calling the Build method of the builder object.

ConfigureWebHostDefaults is an ASP.NET Core specific method that adds some ASP.NET Core specific definitions and configurations. It then uses the methods defined in the Startup.cs class to allow us to configure both the ASP.NET Core pipeline (Configure method) and the dependency injection container (ConfigureServices method).

When the Host is built all definitions ...