Avatar ·

AddTransient、AddScoped和AddSingleton在ASP.NET Core中的区别

大家好!我是ASP.NET Core的新手,正在尝试理解依赖注入(Dependency Injection)。在Startup.cs中,我经常看到三个方法:AddTransient、AddScoped和AddSingleton。我读过文档,但还不完全明白什么时候该用哪个。 例如,我有一个简单的随机数生成服务: ```csharp public interface IRandomService { int GetRandomNumber(); } public class RandomService : IRandomService { private readonly int _number; public RandomService() { _number = new Random().Next(1, 1000); Console.WriteLine($"创建了RandomService实例,数字为{_number}"); } public int GetRandomNumber() => _number; } ``` 我在Startup.cs中这样注册它: ```csharp services.AddTransient(); // 或 services.AddScoped(); // 或 services.AddSingleton(); ``` 当我调用这个服