Microsoft.Extensions.DependencyInjection

Namespace: Microsoft.Extensions.DependencyInjection

IServiceScope

Represents a scope for a set of service dependencies.

Interface

public interface IServiceScope

Properties

Methods

Remarks

Examples

C# Example

// Assuming you have an IServiceProvider configured
var serviceProvider = GetConfiguredServiceProvider();

// Create a new scope
using (var scope = serviceProvider.CreateScope())
{
    // Get services from the scope
    var myScopedService = scope.ServiceProvider.GetService<IScopedService>();
    var myTransientService = scope.ServiceProvider.GetService<ITransientService>();

    // Use the services
    myScopedService.DoSomething();
    myTransientService.DoSomething();
} // scope is automatically disposed here, releasing scoped and transient services

// Getting a transient service outside the scope will create a new instance
var anotherTransientService = serviceProvider.GetService<ITransientService>();
anotherTransientService.DoSomething();

F# Example

// Assuming you have an IServiceProvider configured
let serviceProvider = get_ConfiguredServiceProvider()

// Create a new scope
use scope = serviceProvider.CreateScope() do
    // Get services from the scope
    let myScopedService = scope.ServiceProvider.GetService<IScopedService>()
    let myTransientService = scope.ServiceProvider.GetService<ITransientService>()

    // Use the services
    myScopedService.DoSomething()
    myTransientService.DoSomething()
// scope is automatically disposed here, releasing scoped and transient services

// Getting a transient service outside the scope will create a new instance
let anotherTransientService = serviceProvider.GetService<ITransientService>()
anotherTransientService.DoSomething()

VB.NET Example

' Assuming you have an IServiceProvider configured
Dim serviceProvider As IServiceProvider = GetConfiguredServiceProvider()

' Create a new scope
Using scope As IServiceScope = serviceProvider.CreateScope()
    ' Get services from the scope
    Dim myScopedService As IScopedService = scope.ServiceProvider.GetService(Of IScopedService)()
    Dim myTransientService As ITransientService = scope.ServiceProvider.GetService(Of ITransientService)()

    ' Use the services
    myScopedService.DoSomething()
    myTransientService.DoSomething()
End Using ' scope is automatically disposed here, releasing scoped and transient services

' Getting a transient service outside the scope will create a new instance
Dim anotherTransientService As ITransientService = serviceProvider.GetService(Of ITransientService)()
anotherTransientService.DoSomething()