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?
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
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.
The DI middleware itself doesn’t try to guess the scope. ASP.NET Core middleware explicitly creates a new scope when needed.
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