Member-only story

Dependency Injection and using AddTransient, AddScoped and AddSingleton in an ASP.NET Core application.

Alex
9 min readNov 29, 2023

Within this tutorial I will give a brief explaination of what dependency injection is, with an example. I will also explain and give examples of 3 methods called AddTransient, AddScoped and AddSingleton which are used to define the lifetime of the services.

Knowing what is dependency injection is and how it works is integral to understanding ASP.NET Core applications.

Dependency Injection

Dependency Injection is a software design pattern/technique for achieving Inversion of Control (IoC) between classes and its dependencies, enabling developers to achieve loosely coupled code. Furthermore, dependency injection reduces hard-coded dependencies among your classes by injecting the dependencies at runtime instead of design time.

Below I will show an example of constructor injection within an ASP.NET Core.

So open your favourite IDE (mine is Rider) and create a Console application.

Once you have created the application within the root of the project create a class called “Person.cs” and paste in the below code.

public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }…

--

--

No responses yet