Junior — Middle
Kuidas määratakse objekti olemasoluperiood pärast selle rakendamist sõltuvuste injekteerimise mehhanismi kaudu?
sobes.tech AI
Vastus AI-lt
The lifetime of an object created via Dependency Injection (DI) is determined by the lifetime setting, which is specified during service registration in the DI container. In C# (for example, in ASP.NET Core), there are three main types of lifetime:
- Transient — a new instance is created for each service request.
- Scoped — one instance is created per scope (e.g., per HTTP request) and reused within that scope.
- Singleton — one instance is created at the first request and lives until the application ends.
Registration example:
services.AddTransient<IMyService, MyService>();
services.AddScoped<IMyService, MyService>();
services.AddSingleton<IMyService, MyService>();
Therefore, the object's lifetime depends on the chosen lifetime during registration in the DI container.