<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.0-preview.3.25171.5" />

ServiceProviderServiceExtensions

public static class ServiceProviderServiceExtensions
Extension methods for getting services from an IServiceProvider.
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace Microsoft.Extensions.DependencyInjection { [NullableContext(1)] [Nullable(0)] public static class ServiceProviderServiceExtensions { [NullableContext(2)] public static T GetService<T>([Nullable(1)] this IServiceProvider provider) { System.ThrowHelper.ThrowIfNull(provider, "provider"); return (T)provider.GetService(typeof(T)); } public static object GetRequiredService(this IServiceProvider provider, Type serviceType) { System.ThrowHelper.ThrowIfNull(provider, "provider"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); ISupportRequiredService supportRequiredService = provider as ISupportRequiredService; if (supportRequiredService != null) return supportRequiredService.GetRequiredService(serviceType); object service = provider.GetService(serviceType); if (service == null) throw new InvalidOperationException(System.SR.Format(System.SR.NoServiceRegistered, serviceType)); return service; } public static T GetRequiredService<T>(this IServiceProvider provider) { System.ThrowHelper.ThrowIfNull(provider, "provider"); return (T)provider.GetRequiredService(typeof(T)); } public static IEnumerable<T> GetServices<[Nullable(2)] T>(this IServiceProvider provider) { System.ThrowHelper.ThrowIfNull(provider, "provider"); return provider.GetRequiredService<IEnumerable<T>>(); } [RequiresDynamicCode("The native code for an IEnumerable<serviceType> might not be available at runtime.")] [return: Nullable(new byte[] { 1, 2 })] public static IEnumerable<object> GetServices(this IServiceProvider provider, Type serviceType) { System.ThrowHelper.ThrowIfNull(provider, "provider"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); Type serviceType2 = typeof(IEnumerable<>).MakeGenericType(serviceType); return (IEnumerable<object>)provider.GetRequiredService(serviceType2); } public static IServiceScope CreateScope(this IServiceProvider provider) { return provider.GetRequiredService<IServiceScopeFactory>().CreateScope(); } public static AsyncServiceScope CreateAsyncScope(this IServiceProvider provider) { return new AsyncServiceScope(provider.CreateScope()); } public static AsyncServiceScope CreateAsyncScope(this IServiceScopeFactory serviceScopeFactory) { return new AsyncServiceScope(serviceScopeFactory.CreateScope()); } } }