<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.0-rc.2.24473.5" />

ServiceProviderKeyedServiceExtensions

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 ServiceProviderKeyedServiceExtensions { [NullableContext(2)] public static T GetKeyedService<T>([Nullable(1)] this IServiceProvider provider, object serviceKey) { System.ThrowHelper.ThrowIfNull(provider, "provider"); IKeyedServiceProvider keyedServiceProvider = provider as IKeyedServiceProvider; if (keyedServiceProvider != null) return (T)keyedServiceProvider.GetKeyedService(typeof(T), serviceKey); throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } public static object GetRequiredKeyedService(this IServiceProvider provider, Type serviceType, [Nullable(2)] object serviceKey) { System.ThrowHelper.ThrowIfNull(provider, "provider"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); IKeyedServiceProvider keyedServiceProvider = provider as IKeyedServiceProvider; if (keyedServiceProvider != null) return keyedServiceProvider.GetRequiredKeyedService(serviceType, serviceKey); throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } public static T GetRequiredKeyedService<T>(this IServiceProvider provider, [Nullable(2)] object serviceKey) { System.ThrowHelper.ThrowIfNull(provider, "provider"); return (T)provider.GetRequiredKeyedService(typeof(T), serviceKey); } public static IEnumerable<T> GetKeyedServices<[Nullable(2)] T>(this IServiceProvider provider, [Nullable(2)] object serviceKey) { System.ThrowHelper.ThrowIfNull(provider, "provider"); return provider.GetRequiredKeyedService<IEnumerable<T>>(serviceKey); } [RequiresDynamicCode("The native code for an IEnumerable<serviceType> might not be available at runtime.")] [return: Nullable(new byte[] { 1, 2 })] public static IEnumerable<object> GetKeyedServices(this IServiceProvider provider, Type serviceType, [Nullable(2)] object serviceKey) { System.ThrowHelper.ThrowIfNull(provider, "provider"); System.ThrowHelper.ThrowIfNull(serviceType, "serviceType"); Type serviceType2 = typeof(IEnumerable<>).MakeGenericType(serviceType); return (IEnumerable<object>)provider.GetRequiredKeyedService(serviceType2, serviceKey); } } }