Dependency injection code example for ASP.NET Core

We have a number of dependency injection tutorials which include explaining the different service lifetimes, injecting services into classes, keyed services, creating a new scope, unit testing and the common mistakes of dependency injection.

Download the code example

You'll need to fill out the code example form. We will send you an email where you can download the code example.

The code example will be in a zip file and will include all the dependency injection tutorials separated by a numeric folder name.

Software

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

Tutorials

Here are the different dependency injection tutorials available:

How to use lifetimes in ASP.NET Core dependency injection?

You can read more about how to use the different lifetimes in ASP.NET Core or you can watch the video:

In Visual Studio, open up 01/RoundTheCode.DI._01.sln from the code example zip file that you downloaded.

You can test the different ways to register a service by changing the dependencyTypeEnum variable in Program.cs.  You can change it to:

  • Type - This registers a service by providing the types as parameters
  • Generic - This registers a service by providing the types using the generic class extension method
  • ImplementationType - Allows you to explicitly create the service instance. The types are provided as parameters.
  • ImplementationGeneric - Allows you to explicitly create the service instance. The types are provided using the generic class extension method

Run the application and it will load up the Scalar OpenAPI document on https://localhost:7058/scalar/v1.

To test the differences with the singleton, scoped and transient, run https://localhost:7058/api/WebApi/service-lifetimes.

If you want to test how the transient service lifetime works when injected into a different part of the request, run https://localhost:7058/mvc/service-lifetimes.