Avatar ·

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