This repository is reserved to provide an explanation of the three types of lifecycles modes used in Dependency Injection, in this case w/ .NET Core. The modes are Singleton, Scoped and Transient.
- Only one service instance was created during the app lifecycle.
- All requests to obtain this object will return the same instance.
- It's useful for objects shared by application, such as database connections or global configs.
- We get a new instance with every request, or "Scope".
- Within the same scope, all requests will return the same instace of the object.
- It's useful for sharing resources during request processing without global sharing, as in web app.
- Is created every time it's requested.
- Each request to obtain this object will return a new instance.
- Useful for objects that don't need to be shared between different parts of the app.
In this small project, you'll find three endpoints
In each of them, a service with a specific lifecycle mode was registered and this simple service returns the creation date of the object instance.
An only instance of SingletonService is created and shared across all requests
builder.Services.AddSingleton<ISingletonService, SingletonService>()
Response body
{
"creationDateTime": "2024-05-14 17:43:00.743"
}
Two requests will have different instances of ScopedService and they return the same creation time because they are created in the same scope
builder.Services.AddScoped<IScopedService, ScopedService>()
Response body
{
"firstInstanceDateTime": "2024-05-14 17:57:37.145",
"secondInstanceDateTime": "2024-05-14 17:57:37.145",
"areEqual": true
}
Two requests will have different instances of TransientService and they return different creation times
builder.Services.AddTransient<ITransientService, TransientService>()
Response body
{
"firstInstanceDateTime": "2024-05-14 17:58:02.964",
"secondInstanceDateTime": "2024-05-14 17:58:07.964",
"areEqual": false
}
- Clone this repo: https://github.com/kmlyteixeira/singleton-scoped-transient-dotnet
- Run
dotnet build
to build this project - Run
dotnet run
- Open
http://localhost:5225/swagger
and be happy :)
1️⃣ Dependency injection in ASP.NET Core
3️⃣ Differences Between Scoped, Transient, And Singleton Service