skip to Main Content

I know how scoped dependencies are used in ASP.Net but I was wondering how the dependency injection actually figures out the scope when a service is requested?

Is the scope related to a persistent http connection?

2

Answers


  1. In ASP.NET, the lifetime of scoped dependencies is the duration of a single request i.e. a scope dependency will remain "alive" until the server has responded to a given client request.

    Login or Signup to reply.
  2. The DI middleware itself doesn’t try to guess the scope. ASP.NET Core middleware explicitly creates a new scope when needed.

    • In ASP.NET Core MVC, Web API, Razor Pages and Blazor WASM, that scope is the client request. I think the relevant source is in the RequestServicesFeature class
    • In Blazor Server the scope is the entire user session/channel

    For middleware, the DI scope matters if you register a middleware class. By default a middleware class is Singleton unless it implements the IMiddleware interface. Such middleware is called Factory-activated middleware and the default policy is to use scoped services

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search