Dependency injection in ASP.NET Core

ASP.NET Core implements the dependency injection (DI) design pattern.

We can inject services into a class, and in Razor views.

This makes it ideal to test in an MVC application, because we can inject these services in a controller, and also the view.

This means that we can compare the instances for both the controller and the view for each service lifetime, and see how they differ.

Now, for this example, we have used DI in an ASP.NET Core Model-View-Controller (MVC) application in .NET 5.

We have created three different services, with each service representing one of the service lifetime's available in DI. This includes singleton, scoped and transient.

From there, these services are injected into a controller and into the subsequent view.

Time property is declared with these services and the current time is set when each service is initialised.

From that, we can get this Time property's value from the controller and view, and output it to the view to see the comparison.

Software

This is the software that will need to be installed onto your machine.

Get The Application Working

These are the steps to get the application working.

  • Fill out the code example form. We will send you an email where you can download the code example.

You are now ready to go.

Open the Project in Visual Studio

Open up RoundTheCode.Di.sln in Visual Studio.

You should find that the web application runs on https://localhost:4000.

Start the project in Visual Studio.

Open up a browser and navigate to https://localhost:4000/di. This will output the Time's property from the singleton, scoped and transient service that we set up.

Also, not only will it output the time's property when these services are injected from the controller, it will also show the time's property when injected into the subsequent view.

More Information

You can read more information by viewing our "How to Implement Dependency Injection in ASP.NET Core" article.

In-addition, watch our video tutorial, where we test out dependency injection in an ASP.NET Core MVC application.