Sobes.tech
Junior — Middle

Mis vahe on Scoped ja Transient objektide nähtavuspiirkonnal sõltuvuste sisestamise kontekstis?

sobes.tech AI

Vastus AI-lt

In the context of Dependency Injection in C#, the Scoped and Transient scopes determine the lifetime of created objects:

  • Transient: the object is created anew each time it is requested. This means that on each service call or injection, a new instance will be created.

  • Scoped: the object is created once per request (scope). In web applications, this usually means that within a single HTTP request, the same instance is used, but for another request, a new one is created.

Example:

services.AddTransient<IMyService, MyService>(); // new object per request
services.AddScoped<IMyService, MyService>();   // one object per HTTP request

Thus, Scoped is convenient for maintaining state within a single request, while Transient is suitable for stateless services where a new instance is needed each time.