The scope is a crucial concept in .NET Core dependency injection (DI). It determines the lifecycle and visibility of the services that are injected into your application. Understanding how scope works can help you manage resources more efficiently and avoid common pitfalls, such as memory leaks and unnecessary object creation. In this article, we will explore what scope is, the different types of scopes available in .NET Core, and how to use them with practical examples.
Types of Scopes in .NET Core
- Transient: A new instance of the service is created every time it is requested.
- Scoped: A single instance of the service is created per request (or per scope).
- Singleton: A single instance of the service is created and shared throughout the application's lifetime.
Using Scope in .NET Core
Let's dive into how to use these scopes with examples.
1. Transient
A transient service is created each time it is requested. This is useful for lightweight, stateless services.
public interface ITransientService
{
Guid GetOperationId();
}
public class TransientService : ITransientService
{
private readonly Guid _operationId;
public TransientService()
{
_operationId = Guid.NewGuid();
}
public Guid GetOperationId() => _operationId;
}
Register the service in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ITransientService, TransientService>();
}
Use the service in a controller
[ApiController]
[Route("api/[controller]")]
public class ExampleController : ControllerBase
{
private readonly ITransientService _transientService1;
private readonly ITransientService _transientService2;
public ExampleController(
ITransientService transientService1,
ITransientService transientService2)
{
_transientService1 = transientService1;
_transientService2 = transientService2;
}
[HttpGet]
public IActionResult Get()
{
return Ok(new
{
Service1 = _transientService1.GetOperationId(),
Service2 = _transientService2.GetOperationId()
});
}
}
Each time you hit the endpoint, you'll see different GUIDs for each service instance.
2. Scoped
A scoped service is created once per request. This is useful for services that maintain state within a single request.
public interface IScopedService
{
Guid GetOperationId();
}
public class ScopedService : IScopedService
{
private readonly Guid _operationId;
public ScopedService()
{
_operationId = Guid.NewGuid();
}
public Guid GetOperationId() => _operationId;
}

Join the conversation! Your thoughts help the community grow.