What is a scoped service in ASP.NET Core
a scoped service is one of the 3 service lifetime types available in the default dotnet DI framework.
The other two are Singleton and Transient (we'll look at them later)
As the name suggests, when you inject a service registered as a scoped service, the instance of that service will have a scoped lifetime.
But, what is a scope?
A scope is like a boundary within which the same instance is reused no matter how many times that service is invoked.
For a Web API, the default scope is the request scope. Which means if you create a scoped service and call in a request the same instance is used within that request lifetime.
Once the request is completed, the service instance is destroyed.
How do I create a custom Scope?
Sometimes you might need to create a custom scope for such a service to be invoked (like calling a scoped service inside a singleton service).
In such cases you use IServiceProvider.CreateScope() method. This creates a temporary scope for you and within this you can request and use a scoped service. This is a disposable block, so the service instance is destroyed once out of the CreateScope() block.
One good example of a Scoped Service is the DbContext you register. It's scoped by default.