METHOD

ServiceProviderServiceExtensions.CreateAsyncScope

Creates a scope that supports asynchronous disposal. Resolve scoped services through scope.ServiceProvider. Await disposal when owned services implement asynchronous cleanup. Requires the DI implementation or ASP.NET Core shared framework.

Formal Syntax & Structure

csharp syntaxcsharp
await using var scope = provider.CreateAsyncScope();

Working Example

Example Snippetcsharp
using System;using System.IO;using System.Collections.Generic;using System.Net;using System.Net.Http;using System.Net.Http.Headers;using System.Threading;using Microsoft.Extensions.DependencyInjection;await using var provider = new ServiceCollection().BuildServiceProvider();await using var scope = provider.CreateAsyncScope();Console.WriteLine(scope.ServiceProvider is not null); // True
C# & .NET Reference