Sobes.tech
Junior — Middle

Kuidas toimub mitme samaaegselt täidetava päringu töötlemine Scoped üheprotsessilise konteksti raames?

sobes.tech AI

Vastus AI-lt

In a single-process context with Scoped dependencies in ASP.NET Core, each HTTP request receives its own instance of services with a Scoped scope. When multiple requests are executed simultaneously in the same process, a separate Scoped container is created for each request, isolated from others.

This is achieved through the DI container mechanism, which creates a new scope at the beginning of the request and destroys it at the end. Thus, even in a single-process application, each request works with its own set of Scoped services, preventing data conflicts between requests.

Approximately like this:

// In Startup.cs
services.AddScoped<IMyService, MyService>();

// During processing of each request, a new scope is created
app.Use(async (context, next) => {
    using (var scope = app.ApplicationServices.CreateScope())
    {
        var myService = scope.ServiceProvider.GetRequiredService<IMyService>();
        // Usage of myService within the request
        await next();
    }
});

In reality, ASP.NET Core automatically creates a scope for each HTTP request, so developers usually do not need to create it manually.