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.
This is the software that will need to be installed onto your machine.
- Visual Studio 2019. Version 16.8.4 or above (may work with lower versions). It will work with the free community version.
- .NET 5.0 SDK, or above.
Get The Application Working
These are the steps to get the application working.
- Fill out the Download the Source Code form. We will send you an email where you can download the source code.
You are now ready to go.
Open the Project in Visual Studio
RoundTheCode.Di.sln in Visual Studio.
You should find that the web application runs on
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.
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.