What is a scoped service in ASP.NET Core

Sriram Kumar Mannava
2 min readMar 2, 2023

--

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.

How to create a custom scope in dotnet core

One good example of a Scoped Service is the DbContext you register. It's scoped by default.

--

--

Sriram Kumar Mannava
Sriram Kumar Mannava

Written by Sriram Kumar Mannava

I make Full Stack Development Easy for You | Full Stack .NET Dev | 3× AWS Certified | Blogger

No responses yet