What is the difference between AddTransient, AddScoped and AddSingleton in ASP.NET Core?
Hi everyone! I'm new to ASP.NET Core and trying to understand Dependency Injection. In Startup.cs I often see three methods: AddTransient, AddScoped and AddSingleton. I've read the documentation but I don't fully understand when to use which.
For example, I have a simple service for generating random numbers:
```csharp
public interface IRandomService
{
int GetRandomNumber();
}
public class RandomService : IRandomService
{
private readonly int _number;
public RandomService()
{
_number = new Random().Next(1, 1000);
Console.WriteLine($"Created RandomService instance with number {_number}");
}
public int GetRandomNumber() => _number;
}
```
I register it in Startup.cs like this:
```csharp
services.AddTr
No answers yet.
Log in to leave an answer
Blogs
How to Write a REST API in Kotlin in 30 Minutes: A Practical Guide
Design Patterns in Kotlin: From A to Z with Code Examples
API Gateway for Swift Services: How to Unite Microservices into a Single System
iOS app crashes with dyld: Library not loaded? Solution 2025