Sobes.tech
Junior — Middle

What is the purpose of the AddScoped service in the context of dependency injection?

sobes.tech AI

Answer from AI

AddScoped is a method for registering a service in the dependency injection container in ASP.NET Core, which creates an instance of the service for the duration of a single request (scope). This means that during the processing of one HTTP request, the same instance of the service will be used, and a new one will be created for the next request.

This is useful when you need to preserve state or cache within a single request, but not between different requests.

Registration example:

services.AddScoped<IMyService, MyService>();

Thus, each HTTP request will get its own instance of MyService, which helps control the lifetime of objects and manage resources.