using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading.Tasks; using FxResources.Microsoft.Extensions.DependencyInjection.Abstractions; using Microsoft.CodeAnalysis; using Microsoft.Extensions.Internal; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Extensions.DependencyInjection.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: AssemblyDefaultAlias("Microsoft.Extensions.DependencyInjection.Abstractions")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: AssemblyMetadata("IsAotCompatible", "True")] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Abstractions for dependency injection.\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.DependencyInjection.IServiceCollection")] [assembly: AssemblyFileVersion("10.0.1126.37416")] [assembly: AssemblyInformationalVersion("10.0.11+e2f47b0110ed922f21a1522da67279133ce28f32")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("Microsoft.Extensions.DependencyInjection.Abstractions")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")] [assembly: AssemblyVersion("10.0.0.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class ExtensionMarkerAttribute : Attribute { public ExtensionMarkerAttribute(string name) { } } } namespace FxResources.Microsoft.Extensions.DependencyInjection.Abstractions { internal static class SR { } } namespace System { internal static class SR { private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue(); private static ResourceManager s_resourceManager; internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR))); internal static string AmbiguousConstructorMatch => GetResourceString("AmbiguousConstructorMatch"); internal static string CannotResolveService => GetResourceString("CannotResolveService"); internal static string NoConstructorMatch => GetResourceString("NoConstructorMatch"); internal static string NoServiceRegistered => GetResourceString("NoServiceRegistered"); internal static string ServiceCollectionReadOnly => GetResourceString("ServiceCollectionReadOnly"); internal static string TryAddIndistinguishableTypeToEnumerable => GetResourceString("TryAddIndistinguishableTypeToEnumerable"); internal static string MultipleCtorsMarkedWithAttribute => GetResourceString("MultipleCtorsMarkedWithAttribute"); internal static string MarkedCtorMissingArgumentTypes => GetResourceString("MarkedCtorMissingArgumentTypes"); internal static string CannotCreateAbstractClasses => GetResourceString("CannotCreateAbstractClasses"); internal static string MultipleCtorsFoundWithBestLength => GetResourceString("MultipleCtorsFoundWithBestLength"); internal static string UnableToResolveService => GetResourceString("UnableToResolveService"); internal static string CtorNotLocated => GetResourceString("CtorNotLocated"); internal static string MultipleCtorsFound => GetResourceString("MultipleCtorsFound"); internal static string KeyedServicesNotSupported => GetResourceString("KeyedServicesNotSupported"); internal static string NonKeyedDescriptorMisuse => GetResourceString("NonKeyedDescriptorMisuse"); private static bool GetUsingResourceKeysSwitchValue() { if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled)) { return false; } return isEnabled; } internal static bool UsingResourceKeys() { return s_usingResourceKeys; } private static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } return result; } private static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } internal static string Format(IFormatProvider? provider, string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(provider, resourceFormat, p1, p2, p3); } internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(provider, resourceFormat, args); } return resourceFormat; } } internal static class ExceptionPolyfills { [SpecialName] public sealed class $E6188BA5B951F1F7AA9135E0EBB76F2B { [SpecialName] public static class $96F0261AC622664B8B003966835C0332 { } [ExtensionMarker("$96F0261AC622664B8B003966835C0332")] public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { throw null; } } [SpecialName] public sealed class $3F30F31B33543D5FB8E174FB4FD780B9 { [SpecialName] public static class $1F10CFA08738E6D8AF61CBECC6763DBC { } [ExtensionMarker("$1F10CFA08738E6D8AF61CBECC6763DBC")] public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance) { throw null; } [ExtensionMarker("$1F10CFA08738E6D8AF61CBECC6763DBC")] public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type) { throw null; } } public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { ThrowArgumentNullException(paramName); } } [DoesNotReturn] private static void ThrowArgumentNullException(string paramName) { throw new ArgumentNullException(paramName); } public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance) { if (condition) { ThrowObjectDisposedException(instance); } } public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type) { if (condition) { ThrowObjectDisposedException(type); } } [DoesNotReturn] private static void ThrowObjectDisposedException(object instance) { throw new ObjectDisposedException(instance?.GetType().FullName); } [DoesNotReturn] private static void ThrowObjectDisposedException(Type type) { throw new ObjectDisposedException(type?.FullName); } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class LibraryImportAttribute : Attribute { public string LibraryName { get; } public string? EntryPoint { get; set; } public StringMarshalling StringMarshalling { get; set; } public Type? StringMarshallingCustomType { get; set; } public bool SetLastError { get; set; } public LibraryImportAttribute(string libraryName) { LibraryName = libraryName; } } internal enum StringMarshalling { Custom, Utf8, Utf16 } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class, Inherited = false)] internal sealed class CompilerLoweringPreserveAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } } namespace System.Diagnostics.CodeAnalysis { [CompilerLoweringPreserve] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, Interfaces = 0x2000, NonPublicConstructorsWithInherited = 0x4004, NonPublicMethodsWithInherited = 0x8010, NonPublicFieldsWithInherited = 0x10040, NonPublicNestedTypesWithInherited = 0x20100, NonPublicPropertiesWithInherited = 0x40400, NonPublicEventsWithInherited = 0x81000, PublicConstructorsWithInherited = 0x100003, PublicNestedTypesWithInherited = 0x200080, AllConstructors = 0x104007, AllMethods = 0x8018, AllFields = 0x10060, AllNestedTypes = 0x220180, AllProperties = 0x40600, AllEvents = 0x81800, [EditorBrowsable(EditorBrowsableState.Never)] All = -1 } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresDynamicCodeAttribute : Attribute { public bool ExcludeStatics { get; set; } public string Message { get; } public string? Url { get; set; } public RequiresDynamicCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] internal sealed class UnconditionalSuppressMessageAttribute : Attribute { public string Category { get; } public string CheckId { get; } public string? Scope { get; set; } public string? Target { get; set; } public string? MessageId { get; set; } public string? Justification { get; set; } public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } } namespace Microsoft.Extensions.Internal { internal static class ParameterDefaultValue { public static bool TryGetDefaultValue(ParameterInfo parameter, out object? defaultValue) { bool tryToGetDefaultValue; bool num = CheckHasDefaultValue(parameter, out tryToGetDefaultValue); defaultValue = null; if (num) { if (tryToGetDefaultValue) { defaultValue = parameter.DefaultValue; } bool flag = parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == typeof(Nullable<>); if (defaultValue == null && parameter.ParameterType.IsValueType && !flag) { defaultValue = CreateValueType(parameter.ParameterType); } if (defaultValue != null && flag) { Type underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType); if (underlyingType != null && underlyingType.IsEnum) { defaultValue = Enum.ToObject(underlyingType, defaultValue); } } } return num; [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2067:UnrecognizedReflectionPattern", Justification = "CreateValueType is only called on a ValueType. You can always create an instance of a ValueType.")] static object? CreateValueType(Type t) { return RuntimeHelpers.GetUninitializedObject(t); } } public static bool CheckHasDefaultValue(ParameterInfo parameter, out bool tryToGetDefaultValue) { tryToGetDefaultValue = true; try { return parameter.HasDefaultValue; } catch (FormatException) when (parameter.ParameterType == typeof(DateTime)) { tryToGetDefaultValue = false; return true; } } } } namespace Microsoft.Extensions.DependencyInjection { public static class ActivatorUtilities { private readonly struct FactoryParameterContext { public Type ParameterType { get; } public bool HasDefaultValue { get; } public object DefaultValue { get; } public int ArgumentIndex { get; } public object ServiceKey { get; } public FactoryParameterContext(Type parameterType, bool hasDefaultValue, object defaultValue, int argumentIndex, object serviceKey) { ParameterType = parameterType; HasDefaultValue = hasDefaultValue; DefaultValue = defaultValue; ArgumentIndex = argumentIndex; ServiceKey = serviceKey; } } private sealed class ConstructorInfoEx { public readonly ConstructorInfo Info; public readonly ParameterInfo[] Parameters; public readonly bool IsPreferred; private readonly object[] _parameterKeys; public ConstructorInfoEx(ConstructorInfo constructor) { Info = constructor; Parameters = constructor.GetParameters(); IsPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false); for (int i = 0; i < Parameters.Length; i++) { FromKeyedServicesAttribute fromKeyedServicesAttribute = (FromKeyedServicesAttribute)Attribute.GetCustomAttribute(Parameters[i], typeof(FromKeyedServicesAttribute), inherit: false); if (fromKeyedServicesAttribute != null) { if (_parameterKeys == null) { _parameterKeys = new object[Parameters.Length]; } _parameterKeys[i] = fromKeyedServicesAttribute.Key; } } } public bool IsService(IServiceProviderIsService serviceProviderIsService, int parameterIndex) { ParameterInfo parameterInfo = Parameters[parameterIndex]; object[] parameterKeys = _parameterKeys; object obj = ((parameterKeys != null) ? parameterKeys[parameterIndex] : null); if (obj != null) { if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService) { return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, obj); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } return serviceProviderIsService.IsService(parameterInfo.ParameterType); } public object GetService(IServiceProvider serviceProvider, int parameterIndex) { ParameterInfo parameterInfo = Parameters[parameterIndex]; object[] parameterKeys = _parameterKeys; object obj = ((parameterKeys != null) ? parameterKeys[parameterIndex] : null); if (obj != null) { if (serviceProvider is IKeyedServiceProvider keyedServiceProvider) { return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, obj); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } return serviceProvider.GetService(parameterInfo.ParameterType); } } private readonly ref struct ConstructorMatcher { private readonly ConstructorInfoEx _constructor; private readonly object[] _parameterValues; public ConstructorInfoEx ConstructorInfo => _constructor; public ConstructorMatcher(ConstructorInfoEx constructor, object[] parameterValues) { _constructor = constructor; _parameterValues = parameterValues; } public int Match(object[] givenParameters, IServiceProviderIsService serviceProviderIsService) { for (int i = 0; i < givenParameters.Length; i++) { Type c = givenParameters[i]?.GetType(); bool flag = false; for (int j = 0; j < _constructor.Parameters.Length; j++) { if (_parameterValues[j] == null && _constructor.Parameters[j].ParameterType.IsAssignableFrom(c)) { flag = true; _parameterValues[j] = givenParameters[i]; break; } } if (!flag) { return -1; } } for (int k = 0; k < _constructor.Parameters.Length; k++) { if (_parameterValues[k] == null && !_constructor.IsService(serviceProviderIsService, k)) { if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[k], out object defaultValue)) { return -1; } _parameterValues[k] = defaultValue; } } return _constructor.Parameters.Length; } public object CreateInstance(IServiceProvider provider) { for (int i = 0; i < _constructor.Parameters.Length; i++) { if (_parameterValues[i] != null) { continue; } object service = _constructor.GetService(provider, i); if (service == null) { if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[i], out object defaultValue)) { throw new InvalidOperationException(System.SR.Format(System.SR.UnableToResolveService, _constructor.Parameters[i].ParameterType, _constructor.Info.DeclaringType)); } _parameterValues[i] = defaultValue; } else { _parameterValues[i] = service; } } try { return _constructor.Info.Invoke(_parameterValues); } catch (TargetInvocationException ex) when (ex.InnerException != null) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw; } } public void MapParameters(int?[] parameterMap, object[] givenParameters) { for (int i = 0; i < _constructor.Parameters.Length; i++) { if (parameterMap[i].HasValue) { _parameterValues[i] = givenParameters[parameterMap[i].Value]; } } } } private static readonly MethodInfo GetServiceInfo = new Func(GetService).Method; public static object CreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, params object[] parameters) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); if (instanceType.IsAbstract) { throw new InvalidOperationException(System.SR.CannotCreateAbstractClasses); } ConstructorInfoEx[] array = CreateConstructorInfoExs(instanceType); object[] ctorArgs = null; object[] array2 = null; ConstructorMatcher constructorMatcher = default(ConstructorMatcher); IServiceProviderIsService service = provider.GetService(); ConstructorInfoEx constructorInfoEx; if (service != null) { for (int i = 0; i < array.Length; i++) { constructorInfoEx = array[i]; if (!constructorInfoEx.IsPreferred) { continue; } for (int j = i + 1; j < array.Length; j++) { if (array[j].IsPreferred) { ThrowMultipleCtorsMarkedWithAttributeException(); } } InitializeCtorArgValues(ref ctorArgs, constructorInfoEx.Parameters.Length); constructorMatcher = new ConstructorMatcher(constructorInfoEx, ctorArgs); if (constructorMatcher.Match(parameters, service) == -1) { ThrowMarkedCtorDoesNotTakeAllProvidedArguments(); } return constructorMatcher.CreateInstance(provider); } int num = -1; ConstructorMatcher constructorMatcher2 = default(ConstructorMatcher); bool flag = false; for (int k = 0; k < array.Length; k++) { constructorInfoEx = array[k]; InitializeCtorArgValues(ref ctorArgs, constructorInfoEx.Parameters.Length); constructorMatcher = new ConstructorMatcher(constructorInfoEx, ctorArgs); int num2 = constructorMatcher.Match(parameters, service); if (num < num2) { num = num2; if (k == array.Length - 1) { array2 = ctorArgs; } else { array2 = new object[num2]; ctorArgs.CopyTo(array2, 0); } constructorMatcher2 = new ConstructorMatcher(constructorMatcher.ConstructorInfo, array2); flag = false; } else if (num == num2) { flag = true; } } if (num != -1) { if (flag) { throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsFoundWithBestLength, instanceType, num)); } return constructorMatcher2.CreateInstance(provider); } } Type[] array3; if (parameters.Length == 0) { array3 = Type.EmptyTypes; } else { array3 = new Type[parameters.Length]; for (int l = 0; l < array3.Length; l++) { array3[l] = parameters[l]?.GetType(); } } FindApplicableConstructor(instanceType, array3, array, out var matchingConstructor, out var matchingParameterMap); constructorInfoEx = FindConstructorEx(matchingConstructor, array); InitializeCtorArgValues(ref ctorArgs, constructorInfoEx.Parameters.Length); constructorMatcher = new ConstructorMatcher(constructorInfoEx, ctorArgs); constructorMatcher.MapParameters(matchingParameterMap, parameters); return constructorMatcher.CreateInstance(provider); static void InitializeCtorArgValues(ref object[] reference, int length) { if (reference != null && reference.Length == length) { Array.Clear(reference, 0, length); } else { reference = new object[length]; } } } private static ConstructorInfoEx[] CreateConstructorInfoExs([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type) { ConstructorInfo[] constructors = type.GetConstructors(); ConstructorInfoEx[] array = new ConstructorInfoEx[constructors.Length]; for (int i = 0; i < constructors.Length; i++) { array[i] = new ConstructorInfoEx(constructors[i]); } return array; } public static ObjectFactory CreateFactory([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes) { if (!RuntimeFeature.IsDynamicCodeCompiled) { return CreateFactoryReflection(instanceType, argumentTypes); } CreateFactoryInternal(instanceType, argumentTypes, out var provider, out var argumentArray, out var factoryExpressionBody); return Expression.Lambda(factoryExpressionBody, new ParameterExpression[2] { provider, argumentArray }).Compile(); } public static ObjectFactory CreateFactory<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(Type[] argumentTypes) { if (!RuntimeFeature.IsDynamicCodeCompiled) { ObjectFactory factory = CreateFactoryReflection(typeof(T), argumentTypes); return (IServiceProvider serviceProvider, object[] arguments) => (T)factory(serviceProvider, arguments); } CreateFactoryInternal(typeof(T), argumentTypes, out var provider, out var argumentArray, out var factoryExpressionBody); return Expression.Lambda>(factoryExpressionBody, new ParameterExpression[2] { provider, argumentArray }).Compile(); } private static void CreateFactoryInternal([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, out ParameterExpression provider, out ParameterExpression argumentArray, out Expression factoryExpressionBody) { FindApplicableConstructor(instanceType, argumentTypes, null, out var matchingConstructor, out var matchingParameterMap); provider = Expression.Parameter(typeof(IServiceProvider), "provider"); argumentArray = Expression.Parameter(typeof(object[]), "argumentArray"); factoryExpressionBody = BuildFactoryExpression(matchingConstructor, matchingParameterMap, provider, argumentArray); } public static T CreateInstance<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(IServiceProvider provider, params object[] parameters) { return (T)CreateInstance(provider, typeof(T), parameters); } public static T GetServiceOrCreateInstance<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(IServiceProvider provider) { return (T)GetServiceOrCreateInstance(provider, typeof(T)); } public static object GetServiceOrCreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type) { return provider.GetService(type) ?? CreateInstance(provider, type); } private static object GetService(IServiceProvider sp, Type type, Type requiredBy, bool hasDefaultValue, object key) { object obj = ((key == null) ? sp.GetService(type) : GetKeyedService(sp, type, key)); if (obj == null && !hasDefaultValue) { ThrowHelperUnableToResolveService(type, requiredBy); } return obj; } [DoesNotReturn] private static void ThrowHelperUnableToResolveService(Type type, Type requiredBy) { throw new InvalidOperationException(System.SR.Format(System.SR.UnableToResolveService, type, requiredBy)); } private static BlockExpression BuildFactoryExpression(ConstructorInfo constructor, int?[] parameterMap, Expression serviceProvider, Expression factoryArgumentArray) { ParameterInfo[] parameters = constructor.GetParameters(); Expression[] array = new Expression[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { ParameterInfo parameterInfo = parameters[i]; Type parameterType = parameterInfo.ParameterType; object defaultValue; bool flag = ParameterDefaultValue.TryGetDefaultValue(parameterInfo, out defaultValue); if (parameterMap[i].HasValue) { array[i] = Expression.ArrayAccess(factoryArgumentArray, Expression.Constant(parameterMap[i])); } else { FromKeyedServicesAttribute fromKeyedServicesAttribute = (FromKeyedServicesAttribute)Attribute.GetCustomAttribute(parameterInfo, typeof(FromKeyedServicesAttribute), inherit: false); Expression[] arguments = new Expression[5] { serviceProvider, Expression.Constant(parameterType, typeof(Type)), Expression.Constant(constructor.DeclaringType, typeof(Type)), Expression.Constant(flag), Expression.Constant(fromKeyedServicesAttribute?.Key, typeof(object)) }; array[i] = Expression.Call(GetServiceInfo, arguments); } if (flag) { ConstantExpression right = Expression.Constant(defaultValue); array[i] = Expression.Coalesce(array[i], right); } array[i] = Expression.Convert(array[i], parameterType); } return Expression.Block(Expression.IfThen(Expression.Equal(serviceProvider, Expression.Constant(null)), Expression.Throw(Expression.Constant(new ArgumentNullException("serviceProvider")))), Expression.New(constructor, array)); } private static ObjectFactory CreateFactoryReflection([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes) { FindApplicableConstructor(instanceType, argumentTypes, null, out var constructor, out var parameterMap); Type declaringType = constructor.DeclaringType; ParameterInfo[] constructorParameters = constructor.GetParameters(); if (constructorParameters.Length == 0) { return (IServiceProvider serviceProvider, object[] arguments) => constructor.Invoke(BindingFlags.DoNotWrapExceptions, null, null, null); } FactoryParameterContext[] parameters = GetFactoryParameterContext(); return (IServiceProvider serviceProvider, object[] arguments) => ReflectionFactoryCanonical(constructor, parameters, declaringType, serviceProvider, arguments); FactoryParameterContext[] GetFactoryParameterContext() { FactoryParameterContext[] array = new FactoryParameterContext[constructorParameters.Length]; for (int i = 0; i < constructorParameters.Length; i++) { ParameterInfo parameterInfo = constructorParameters[i]; FromKeyedServicesAttribute fromKeyedServicesAttribute = (FromKeyedServicesAttribute)Attribute.GetCustomAttribute(parameterInfo, typeof(FromKeyedServicesAttribute), inherit: false); object defaultValue; bool hasDefaultValue = ParameterDefaultValue.TryGetDefaultValue(parameterInfo, out defaultValue); array[i] = new FactoryParameterContext(parameterInfo.ParameterType, hasDefaultValue, defaultValue, parameterMap[i] ?? (-1), fromKeyedServicesAttribute?.Key); } return array; } } private static void FindApplicableConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, ConstructorInfoEx[] constructors, out ConstructorInfo matchingConstructor, out int?[] matchingParameterMap) { if (!TryFindPreferredConstructor(instanceType, argumentTypes, constructors, out var matchingConstructor2, out var parameterMap) && !TryFindMatchingConstructor(instanceType, argumentTypes, out matchingConstructor2, out parameterMap)) { throw new InvalidOperationException(System.SR.Format(System.SR.CtorNotLocated, instanceType)); } matchingConstructor = matchingConstructor2; matchingParameterMap = parameterMap; } private static ConstructorInfoEx FindConstructorEx(ConstructorInfo constructorInfo, ConstructorInfoEx[] constructorExs) { for (int i = 0; i < constructorExs.Length; i++) { if ((object)constructorExs[i].Info == constructorInfo) { return constructorExs[i]; } } return null; } private static bool TryFindMatchingConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, [NotNullWhen(true)] out ConstructorInfo matchingConstructor, [NotNullWhen(true)] out int?[] parameterMap) { matchingConstructor = null; parameterMap = null; ConstructorInfo[] constructors = instanceType.GetConstructors(); foreach (ConstructorInfo constructorInfo in constructors) { if (TryCreateParameterMap(constructorInfo.GetParameters(), argumentTypes, out var parameterMap2)) { if (matchingConstructor != null) { throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsFound, instanceType)); } matchingConstructor = constructorInfo; parameterMap = parameterMap2; } } if (matchingConstructor != null) { return true; } return false; } private static bool TryFindPreferredConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, ConstructorInfoEx[] constructors, [NotNullWhen(true)] out ConstructorInfo matchingConstructor, [NotNullWhen(true)] out int?[] parameterMap) { bool flag = false; matchingConstructor = null; parameterMap = null; if (constructors == null) { constructors = CreateConstructorInfoExs(instanceType); } ConstructorInfoEx[] array = constructors; foreach (ConstructorInfoEx constructorInfoEx in array) { if (constructorInfoEx.IsPreferred) { if (flag) { ThrowMultipleCtorsMarkedWithAttributeException(); } if (!TryCreateParameterMap(constructorInfoEx.Info.GetParameters(), argumentTypes, out var parameterMap2)) { ThrowMarkedCtorDoesNotTakeAllProvidedArguments(); } matchingConstructor = constructorInfoEx.Info; parameterMap = parameterMap2; flag = true; } } if (matchingConstructor != null) { return true; } return false; } private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters, Type[] argumentTypes, out int?[] parameterMap) { parameterMap = new int?[constructorParameters.Length]; for (int i = 0; i < argumentTypes.Length; i++) { bool flag = false; Type c = argumentTypes[i]; for (int j = 0; j < constructorParameters.Length; j++) { if (!parameterMap[j].HasValue && constructorParameters[j].ParameterType.IsAssignableFrom(c)) { flag = true; parameterMap[j] = i; break; } } if (!flag) { return false; } } return true; } private static void ThrowMultipleCtorsMarkedWithAttributeException() { throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsMarkedWithAttribute, "ActivatorUtilitiesConstructorAttribute")); } private static void ThrowMarkedCtorDoesNotTakeAllProvidedArguments() { throw new InvalidOperationException(System.SR.Format(System.SR.MarkedCtorMissingArgumentTypes, "ActivatorUtilitiesConstructorAttribute")); } private static object ReflectionFactoryCanonical(ConstructorInfo constructor, FactoryParameterContext[] parameters, Type declaringType, IServiceProvider serviceProvider, object[] arguments) { ExceptionPolyfills.ThrowIfNull(serviceProvider, "serviceProvider"); object[] array = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { ref FactoryParameterContext reference = ref parameters[i]; array[i] = ((reference.ArgumentIndex != -1) ? arguments[reference.ArgumentIndex] : GetService(serviceProvider, reference.ParameterType, declaringType, reference.HasDefaultValue, reference.ServiceKey)) ?? reference.DefaultValue; } return constructor.Invoke(BindingFlags.DoNotWrapExceptions, null, array, null); } private static object GetKeyedService(IServiceProvider provider, Type type, object serviceKey) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); if (provider is IKeyedServiceProvider keyedServiceProvider) { return keyedServiceProvider.GetKeyedService(type, serviceKey); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } } [AttributeUsage(AttributeTargets.All)] public class ActivatorUtilitiesConstructorAttribute : Attribute { } [DebuggerDisplay("{ServiceProvider,nq}")] public readonly struct AsyncServiceScope : IServiceScope, IDisposable, IAsyncDisposable { private readonly IServiceScope _serviceScope; public IServiceProvider ServiceProvider => _serviceScope.ServiceProvider; public AsyncServiceScope(IServiceScope serviceScope) { ExceptionPolyfills.ThrowIfNull(serviceScope, "serviceScope"); _serviceScope = serviceScope; } public void Dispose() { _serviceScope.Dispose(); } public ValueTask DisposeAsync() { if (_serviceScope is IAsyncDisposable asyncDisposable) { return asyncDisposable.DisposeAsync(); } _serviceScope.Dispose(); return default(ValueTask); } } [AttributeUsage(AttributeTargets.Parameter)] public class FromKeyedServicesAttribute : Attribute { public object? Key { get; } public ServiceKeyLookupMode LookupMode { get; } public FromKeyedServicesAttribute(object? key) { Key = key; LookupMode = ((key == null) ? ServiceKeyLookupMode.NullKey : ServiceKeyLookupMode.ExplicitKey); } public FromKeyedServicesAttribute() { Key = null; LookupMode = ServiceKeyLookupMode.InheritKey; } } public interface IKeyedServiceProvider : IServiceProvider { object? GetKeyedService(Type serviceType, object? serviceKey); object GetRequiredKeyedService(Type serviceType, object? serviceKey); } public static class KeyedService { private sealed class AnyKeyObj { public override string ToString() { return "*"; } } public static object AnyKey { get; } = new AnyKeyObj(); } public interface IServiceCollection : IList, ICollection, IEnumerable, IEnumerable { } public interface IServiceProviderFactory where TContainerBuilder : notnull { TContainerBuilder CreateBuilder(IServiceCollection services); IServiceProvider CreateServiceProvider(TContainerBuilder containerBuilder); } public interface IServiceProviderIsKeyedService : IServiceProviderIsService { bool IsKeyedService(Type serviceType, object? serviceKey); } public interface IServiceProviderIsService { bool IsService(Type serviceType); } public interface IServiceScope : IDisposable { IServiceProvider ServiceProvider { get; } } public interface IServiceScopeFactory { IServiceScope CreateScope(); } public interface ISupportRequiredService { object GetRequiredService(Type serviceType); } public delegate object ObjectFactory(IServiceProvider serviceProvider, object?[]? arguments); public delegate T ObjectFactory(IServiceProvider serviceProvider, object?[]? arguments); [DebuggerDisplay("{DebuggerToString(),nq}")] [DebuggerTypeProxy(typeof(ServiceCollectionDebugView))] public class ServiceCollection : IServiceCollection, IList, ICollection, IEnumerable, IEnumerable { private sealed class ServiceCollectionDebugView { private readonly ServiceCollection _services; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public ServiceDescriptor[] Items { get { ServiceDescriptor[] array = new ServiceDescriptor[_services.Count]; _services.CopyTo(array, 0); return array; } } public ServiceCollectionDebugView(ServiceCollection services) { _services = services; } } private readonly List _descriptors = new List(); private bool _isReadOnly; public int Count => _descriptors.Count; public bool IsReadOnly => _isReadOnly; public ServiceDescriptor this[int index] { get { return _descriptors[index]; } set { CheckReadOnly(); _descriptors[index] = value; } } public void Clear() { CheckReadOnly(); _descriptors.Clear(); } public bool Contains(ServiceDescriptor item) { return _descriptors.Contains(item); } public void CopyTo(ServiceDescriptor[] array, int arrayIndex) { _descriptors.CopyTo(array, arrayIndex); } public bool Remove(ServiceDescriptor item) { CheckReadOnly(); return _descriptors.Remove(item); } public IEnumerator GetEnumerator() { return _descriptors.GetEnumerator(); } void ICollection.Add(ServiceDescriptor item) { CheckReadOnly(); _descriptors.Add(item); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int IndexOf(ServiceDescriptor item) { return _descriptors.IndexOf(item); } public void Insert(int index, ServiceDescriptor item) { CheckReadOnly(); _descriptors.Insert(index, item); } public void RemoveAt(int index) { CheckReadOnly(); _descriptors.RemoveAt(index); } public void MakeReadOnly() { _isReadOnly = true; } private void CheckReadOnly() { if (_isReadOnly) { ThrowReadOnlyException(); } } private static void ThrowReadOnlyException() { throw new InvalidOperationException(System.SR.ServiceCollectionReadOnly); } private string DebuggerToString() { string text = $"Count = {_descriptors.Count}"; if (_isReadOnly) { text += ", IsReadOnly = true"; } return text; } } public static class ServiceCollectionServiceExtensions { public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Transient); } public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return Add(services, serviceType, implementationFactory, ServiceLifetime.Transient); } public static IServiceCollection AddTransient(this IServiceCollection services) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddTransient(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddTransient(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); return services.AddTransient(serviceType, serviceType); } public static IServiceCollection AddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddTransient(typeof(TService)); } public static IServiceCollection AddTransient(this IServiceCollection services, Func implementationFactory) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddTransient(typeof(TService), implementationFactory); } public static IServiceCollection AddTransient(this IServiceCollection services, Func implementationFactory) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddTransient(typeof(TService), implementationFactory); } public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Scoped); } public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return Add(services, serviceType, implementationFactory, ServiceLifetime.Scoped); } public static IServiceCollection AddScoped(this IServiceCollection services) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddScoped(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddScoped(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); return services.AddScoped(serviceType, serviceType); } public static IServiceCollection AddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddScoped(typeof(TService)); } public static IServiceCollection AddScoped(this IServiceCollection services, Func implementationFactory) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddScoped(typeof(TService), implementationFactory); } public static IServiceCollection AddScoped(this IServiceCollection services, Func implementationFactory) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddScoped(typeof(TService), implementationFactory); } public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); return Add(services, serviceType, implementationType, ServiceLifetime.Singleton); } public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return Add(services, serviceType, implementationFactory, ServiceLifetime.Singleton); } public static IServiceCollection AddSingleton(this IServiceCollection services) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddSingleton(typeof(TService), typeof(TImplementation)); } public static IServiceCollection AddSingleton(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); return services.AddSingleton(serviceType, serviceType); } public static IServiceCollection AddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddSingleton(typeof(TService)); } public static IServiceCollection AddSingleton(this IServiceCollection services, Func implementationFactory) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddSingleton(typeof(TService), implementationFactory); } public static IServiceCollection AddSingleton(this IServiceCollection services, Func implementationFactory) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddSingleton(typeof(TService), implementationFactory); } public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, object implementationInstance) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance"); ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationInstance); services.Add(item); return services; } public static IServiceCollection AddSingleton(this IServiceCollection services, TService implementationInstance) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance"); return services.AddSingleton(typeof(TService), implementationInstance); } private static IServiceCollection Add(IServiceCollection collection, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) { ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationType, lifetime); collection.Add(item); return collection; } private static IServiceCollection Add(IServiceCollection collection, Type serviceType, Func implementationFactory, ServiceLifetime lifetime) { ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationFactory, lifetime); collection.Add(item); return collection; } public static IServiceCollection AddKeyedTransient(this IServiceCollection services, Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Transient); } public static IServiceCollection AddKeyedTransient(this IServiceCollection services, Type serviceType, object? serviceKey, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Transient); } public static IServiceCollection AddKeyedTransient(this IServiceCollection services, object? serviceKey) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddKeyedTransient(typeof(TService), serviceKey, typeof(TImplementation)); } public static IServiceCollection AddKeyedTransient(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); return services.AddKeyedTransient(serviceType, serviceKey, serviceType); } public static IServiceCollection AddKeyedTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services, object? serviceKey) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddKeyedTransient(typeof(TService), serviceKey); } public static IServiceCollection AddKeyedTransient(this IServiceCollection services, object? serviceKey, Func implementationFactory) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedTransient(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedTransient(this IServiceCollection services, object? serviceKey, Func implementationFactory) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedTransient(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedScoped(this IServiceCollection services, Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Scoped); } public static IServiceCollection AddKeyedScoped(this IServiceCollection services, Type serviceType, object? serviceKey, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Scoped); } public static IServiceCollection AddKeyedScoped(this IServiceCollection services, object? serviceKey) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddKeyedScoped(typeof(TService), serviceKey, typeof(TImplementation)); } public static IServiceCollection AddKeyedScoped(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); return services.AddKeyedScoped(serviceType, serviceKey, serviceType); } public static IServiceCollection AddKeyedScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services, object? serviceKey) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddKeyedScoped(typeof(TService), serviceKey); } public static IServiceCollection AddKeyedScoped(this IServiceCollection services, object? serviceKey, Func implementationFactory) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedScoped(this IServiceCollection services, object? serviceKey, Func implementationFactory) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Singleton); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Singleton); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, object? serviceKey) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddKeyedSingleton(typeof(TService), serviceKey, typeof(TImplementation)); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); return services.AddKeyedSingleton(serviceType, serviceKey, serviceType); } public static IServiceCollection AddKeyedSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services, object? serviceKey) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); return services.AddKeyedSingleton(typeof(TService), serviceKey, typeof(TService)); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, object? serviceKey, Func implementationFactory) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, object? serviceKey, Func implementationFactory) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationFactory); } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, object implementationInstance) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance"); ServiceDescriptor item = new ServiceDescriptor(serviceType, serviceKey, implementationInstance); services.Add(item); return services; } public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, object? serviceKey, TService implementationInstance) where TService : class { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance"); return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationInstance); } private static IServiceCollection AddKeyed(IServiceCollection collection, Type serviceType, object serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) { ServiceDescriptor item = new ServiceDescriptor(serviceType, serviceKey, implementationType, lifetime); collection.Add(item); return collection; } private static IServiceCollection AddKeyed(IServiceCollection collection, Type serviceType, object serviceKey, Func implementationFactory, ServiceLifetime lifetime) { ServiceDescriptor item = new ServiceDescriptor(serviceType, serviceKey, implementationFactory, lifetime); collection.Add(item); return collection; } } [DebuggerDisplay("{DebuggerToString(),nq}")] public class ServiceDescriptor { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] private Type _implementationType; private object _implementationInstance; private object _implementationFactory; public ServiceLifetime Lifetime { get; } public object? ServiceKey { get; } public Type ServiceType { get; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] public Type? ImplementationType { get { if (!IsKeyedService) { return _implementationType; } return null; } } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] public Type? KeyedImplementationType { get { if (!IsKeyedService) { ThrowNonKeyedDescriptor(); } return _implementationType; } } public object? ImplementationInstance { get { if (!IsKeyedService) { return _implementationInstance; } return null; } } public object? KeyedImplementationInstance { get { if (!IsKeyedService) { ThrowNonKeyedDescriptor(); } return _implementationInstance; } } public Func? ImplementationFactory { get { if (!IsKeyedService) { return (Func)_implementationFactory; } return null; } } public Func? KeyedImplementationFactory { get { if (!IsKeyedService) { ThrowNonKeyedDescriptor(); } return (Func)_implementationFactory; } } public bool IsKeyedService => ServiceKey != null; public ServiceDescriptor(Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) : this(serviceType, null, implementationType, lifetime) { } public ServiceDescriptor(Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) : this(serviceType, serviceKey, lifetime) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); _implementationType = implementationType; } public ServiceDescriptor(Type serviceType, object instance) : this(serviceType, null, instance) { } public ServiceDescriptor(Type serviceType, object? serviceKey, object instance) : this(serviceType, serviceKey, ServiceLifetime.Singleton) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(instance, "instance"); _implementationInstance = instance; } public ServiceDescriptor(Type serviceType, Func factory, ServiceLifetime lifetime) : this(serviceType, (object)null, lifetime) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(factory, "factory"); _implementationFactory = factory; } public ServiceDescriptor(Type serviceType, object? serviceKey, Func factory, ServiceLifetime lifetime) : this(serviceType, serviceKey, lifetime) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(factory, "factory"); if (serviceKey == null) { Func implementationFactory = (IServiceProvider sp) => factory(sp, null); _implementationFactory = implementationFactory; } else { _implementationFactory = factory; } } private ServiceDescriptor(Type serviceType, object serviceKey, ServiceLifetime lifetime) { Lifetime = lifetime; ServiceType = serviceType; ServiceKey = serviceKey; } public override string ToString() { string text = string.Format("{0}: {1} {2}: {3} ", "ServiceType", ServiceType, "Lifetime", Lifetime); if (IsKeyedService) { text += string.Format("{0}: {1} ", "ServiceKey", ServiceKey); if (KeyedImplementationType != null) { return text + string.Format("{0}: {1}", "KeyedImplementationType", KeyedImplementationType); } if (KeyedImplementationFactory != null) { MethodInfo method = KeyedImplementationFactory.Method; string text2 = method.DeclaringType?.FullName; string name = method.Name; return text + "KeyedImplementationFactory: " + text2 + "." + name; } return text + string.Format("{0}: {1}", "KeyedImplementationInstance", KeyedImplementationInstance); } if (ImplementationType != null) { return text + string.Format("{0}: {1}", "ImplementationType", ImplementationType); } if (ImplementationFactory != null) { MethodInfo method2 = ImplementationFactory.Method; string text3 = method2.DeclaringType?.FullName; string name2 = method2.Name; return text + "ImplementationFactory: " + text3 + "." + name2; } return text + string.Format("{0}: {1}", "ImplementationInstance", ImplementationInstance); } internal Type GetImplementationType() { if (ServiceKey == null) { if (ImplementationType != null) { return ImplementationType; } if (ImplementationInstance != null) { return ImplementationInstance.GetType(); } if (ImplementationFactory != null) { return ImplementationFactory.GetType().GenericTypeArguments[1]; } } else { if (KeyedImplementationType != null) { return KeyedImplementationType; } if (KeyedImplementationInstance != null) { return KeyedImplementationInstance.GetType(); } if (KeyedImplementationFactory != null) { return KeyedImplementationFactory.GetType().GenericTypeArguments[2]; } } return null; } public static ServiceDescriptor Transient() where TService : class where TImplementation : class, TService { return DescribeKeyed((object)null, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient(object? serviceKey) where TService : class where TImplementation : class, TService { return DescribeKeyed(serviceKey, ServiceLifetime.Transient); } public static ServiceDescriptor Transient(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); return Describe(service, implementationType, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Transient); } public static ServiceDescriptor Transient(Func implementationFactory) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient(object? serviceKey, Func implementationFactory) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Transient(Func implementationFactory) where TService : class { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient(object? serviceKey, Func implementationFactory) where TService : class { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Transient(Type service, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(service, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor KeyedTransient(Type service, object? serviceKey, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(service, serviceKey, implementationFactory, ServiceLifetime.Transient); } public static ServiceDescriptor Scoped() where TService : class where TImplementation : class, TService { return DescribeKeyed((object)null, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped(object? serviceKey) where TService : class where TImplementation : class, TService { return DescribeKeyed(serviceKey, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { return Describe(service, implementationType, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped(Func implementationFactory) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped(object? serviceKey, Func implementationFactory) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped(Func implementationFactory) where TService : class { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped(object? serviceKey, Func implementationFactory) where TService : class { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Scoped(Type service, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(service, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor KeyedScoped(Type service, object? serviceKey, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(service, serviceKey, implementationFactory, ServiceLifetime.Scoped); } public static ServiceDescriptor Singleton() where TService : class where TImplementation : class, TService { return DescribeKeyed((object)null, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton(object? serviceKey) where TService : class where TImplementation : class, TService { return DescribeKeyed(serviceKey, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); return Describe(service, implementationType, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton(Func implementationFactory) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton(object? serviceKey, Func implementationFactory) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton(Func implementationFactory) where TService : class { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton(object? serviceKey, Func implementationFactory) where TService : class { ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton(Type serviceType, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return Describe(serviceType, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor KeyedSingleton(Type serviceType, object? serviceKey, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); return DescribeKeyed(serviceType, serviceKey, implementationFactory, ServiceLifetime.Singleton); } public static ServiceDescriptor Singleton(TService implementationInstance) where TService : class { ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance"); return Singleton(typeof(TService), implementationInstance); } public static ServiceDescriptor KeyedSingleton(object? serviceKey, TService implementationInstance) where TService : class { ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance"); return KeyedSingleton(typeof(TService), serviceKey, implementationInstance); } public static ServiceDescriptor Singleton(Type serviceType, object implementationInstance) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance"); return new ServiceDescriptor(serviceType, implementationInstance); } public static ServiceDescriptor KeyedSingleton(Type serviceType, object? serviceKey, object implementationInstance) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance"); return new ServiceDescriptor(serviceType, serviceKey, implementationInstance); } private static ServiceDescriptor DescribeKeyed(object serviceKey, ServiceLifetime lifetime) where TService : class where TImplementation : class, TService { return DescribeKeyed(typeof(TService), serviceKey, typeof(TImplementation), lifetime); } public static ServiceDescriptor Describe(Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) { return new ServiceDescriptor(serviceType, implementationType, lifetime); } public static ServiceDescriptor DescribeKeyed(Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) { return new ServiceDescriptor(serviceType, serviceKey, implementationType, lifetime); } public static ServiceDescriptor Describe(Type serviceType, Func implementationFactory, ServiceLifetime lifetime) { return new ServiceDescriptor(serviceType, implementationFactory, lifetime); } public static ServiceDescriptor DescribeKeyed(Type serviceType, object? serviceKey, Func implementationFactory, ServiceLifetime lifetime) { return new ServiceDescriptor(serviceType, serviceKey, implementationFactory, lifetime); } private string DebuggerToString() { string text = $"Lifetime = {Lifetime}, ServiceType = \"{ServiceType.FullName}\""; if (IsKeyedService) { text += $", ServiceKey = \"{ServiceKey}\""; if (KeyedImplementationType != null) { return text + ", KeyedImplementationType = \"" + KeyedImplementationType.FullName + "\""; } if (KeyedImplementationFactory != null) { return text + $", KeyedImplementationFactory = {KeyedImplementationFactory.Method}"; } return text + $", KeyedImplementationInstance = {KeyedImplementationInstance}"; } if (ImplementationType != null) { return text + ", ImplementationType = \"" + ImplementationType.FullName + "\""; } if (ImplementationFactory != null) { return text + $", ImplementationFactory = {ImplementationFactory.Method}"; } return text + $", ImplementationInstance = {ImplementationInstance}"; } private static void ThrowNonKeyedDescriptor() { throw new InvalidOperationException(System.SR.NonKeyedDescriptorMisuse); } } [AttributeUsage(AttributeTargets.Parameter)] public class ServiceKeyAttribute : Attribute { } public enum ServiceKeyLookupMode { InheritKey, NullKey, ExplicitKey } public enum ServiceLifetime { Singleton, Scoped, Transient } public static class ServiceProviderKeyedServiceExtensions { public static T? GetKeyedService(this IServiceProvider provider, object? serviceKey) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); if (provider is IKeyedServiceProvider keyedServiceProvider) { return (T)keyedServiceProvider.GetKeyedService(typeof(T), serviceKey); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } public static object? GetKeyedService(this IServiceProvider provider, Type serviceType, object? serviceKey) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); if (provider is IKeyedServiceProvider keyedServiceProvider) { return keyedServiceProvider.GetKeyedService(serviceType, serviceKey); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } public static object GetRequiredKeyedService(this IServiceProvider provider, Type serviceType, object? serviceKey) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); if (provider is IKeyedServiceProvider keyedServiceProvider) { return keyedServiceProvider.GetRequiredKeyedService(serviceType, serviceKey); } throw new InvalidOperationException(System.SR.KeyedServicesNotSupported); } public static T GetRequiredKeyedService(this IServiceProvider provider, object? serviceKey) where T : notnull { ExceptionPolyfills.ThrowIfNull(provider, "provider"); return (T)provider.GetRequiredKeyedService(typeof(T), serviceKey); } public static IEnumerable GetKeyedServices(this IServiceProvider provider, object? serviceKey) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); return provider.GetRequiredKeyedService>(serviceKey); } [RequiresDynamicCode("The native code for an IEnumerable might not be available at runtime.")] public static IEnumerable GetKeyedServices(this IServiceProvider provider, Type serviceType, object? serviceKey) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); Type serviceType2 = typeof(IEnumerable<>).MakeGenericType(serviceType); return (IEnumerable)provider.GetRequiredKeyedService(serviceType2, serviceKey); } } public static class ServiceProviderServiceExtensions { public static T? GetService(this IServiceProvider provider) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); return (T)provider.GetService(typeof(T)); } public static object GetRequiredService(this IServiceProvider provider, Type serviceType) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); if (provider is ISupportRequiredService supportRequiredService) { return supportRequiredService.GetRequiredService(serviceType); } return provider.GetService(serviceType) ?? throw new InvalidOperationException(System.SR.Format(System.SR.NoServiceRegistered, serviceType)); } public static T GetRequiredService(this IServiceProvider provider) where T : notnull { ExceptionPolyfills.ThrowIfNull(provider, "provider"); return (T)provider.GetRequiredService(typeof(T)); } public static IEnumerable GetServices(this IServiceProvider provider) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); return provider.GetRequiredService>(); } [RequiresDynamicCode("The native code for an IEnumerable might not be available at runtime.")] public static IEnumerable GetServices(this IServiceProvider provider, Type serviceType) { ExceptionPolyfills.ThrowIfNull(provider, "provider"); ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); Type serviceType2 = typeof(IEnumerable<>).MakeGenericType(serviceType); return (IEnumerable)provider.GetRequiredService(serviceType2); } public static IServiceScope CreateScope(this IServiceProvider provider) { return provider.GetRequiredService().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()); } } } namespace Microsoft.Extensions.DependencyInjection.Extensions { public static class ServiceCollectionDescriptorExtensions { public static IServiceCollection Add(this IServiceCollection collection, ServiceDescriptor descriptor) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(descriptor, "descriptor"); collection.Add(descriptor); return collection; } public static IServiceCollection Add(this IServiceCollection collection, IEnumerable descriptors) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(descriptors, "descriptors"); foreach (ServiceDescriptor descriptor in descriptors) { collection.Add(descriptor); } return collection; } public static void TryAdd(this IServiceCollection collection, ServiceDescriptor descriptor) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(descriptor, "descriptor"); int count = collection.Count; for (int i = 0; i < count; i++) { if (collection[i].ServiceType == descriptor.ServiceType && object.Equals(collection[i].ServiceKey, descriptor.ServiceKey)) { return; } } collection.Add(descriptor); } public static void TryAdd(this IServiceCollection collection, IEnumerable descriptors) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(descriptors, "descriptors"); foreach (ServiceDescriptor descriptor in descriptors) { collection.TryAdd(descriptor); } } public static void TryAddTransient(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, service); collection.TryAdd(descriptor); } public static void TryAddTransient(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationType); collection.TryAdd(descriptor); } public static void TryAddTransient(this IServiceCollection collection, Type service, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { ExceptionPolyfills.ThrowIfNull(collection, "collection"); collection.TryAddTransient(typeof(TService), typeof(TService)); } public static void TryAddTransient(this IServiceCollection collection) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(collection, "collection"); collection.TryAddTransient(typeof(TService), typeof(TImplementation)); } public static void TryAddTransient(this IServiceCollection services, Func implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.Transient(implementationFactory)); } public static void TryAddScoped(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, service); collection.TryAdd(descriptor); } public static void TryAddScoped(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationType); collection.TryAdd(descriptor); } public static void TryAddScoped(this IServiceCollection collection, Type service, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { ExceptionPolyfills.ThrowIfNull(collection, "collection"); collection.TryAddScoped(typeof(TService), typeof(TService)); } public static void TryAddScoped(this IServiceCollection collection) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(collection, "collection"); collection.TryAddScoped(typeof(TService), typeof(TImplementation)); } public static void TryAddScoped(this IServiceCollection services, Func implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.Scoped(implementationFactory)); } public static void TryAddSingleton(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, service); collection.TryAdd(descriptor); } public static void TryAddSingleton(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationType); collection.TryAdd(descriptor); } public static void TryAddSingleton(this IServiceCollection collection, Type service, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { ExceptionPolyfills.ThrowIfNull(collection, "collection"); collection.TryAddSingleton(typeof(TService), typeof(TService)); } public static void TryAddSingleton(this IServiceCollection collection) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(collection, "collection"); collection.TryAddSingleton(typeof(TService), typeof(TImplementation)); } public static void TryAddSingleton(this IServiceCollection collection, TService instance) where TService : class { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(instance, "instance"); ServiceDescriptor descriptor = ServiceDescriptor.Singleton(typeof(TService), instance); collection.TryAdd(descriptor); } public static void TryAddSingleton(this IServiceCollection services, Func implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.Singleton(implementationFactory)); } public static void TryAddEnumerable(this IServiceCollection services, ServiceDescriptor descriptor) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(descriptor, "descriptor"); Type implementationType = descriptor.GetImplementationType(); if (implementationType == typeof(object) || implementationType == descriptor.ServiceType) { throw new ArgumentException(System.SR.Format(System.SR.TryAddIndistinguishableTypeToEnumerable, implementationType, descriptor.ServiceType), "descriptor"); } int count = services.Count; for (int i = 0; i < count; i++) { ServiceDescriptor serviceDescriptor = services[i]; if (serviceDescriptor.ServiceType == descriptor.ServiceType && serviceDescriptor.GetImplementationType() == implementationType && object.Equals(serviceDescriptor.ServiceKey, descriptor.ServiceKey)) { return; } } services.Add(descriptor); } public static void TryAddEnumerable(this IServiceCollection services, IEnumerable descriptors) { ExceptionPolyfills.ThrowIfNull(services, "services"); ExceptionPolyfills.ThrowIfNull(descriptors, "descriptors"); foreach (ServiceDescriptor descriptor in descriptors) { services.TryAddEnumerable(descriptor); } } public static IServiceCollection Replace(this IServiceCollection collection, ServiceDescriptor descriptor) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(descriptor, "descriptor"); int count = collection.Count; for (int i = 0; i < count; i++) { if (collection[i].ServiceType == descriptor.ServiceType && object.Equals(collection[i].ServiceKey, descriptor.ServiceKey)) { collection.RemoveAt(i); break; } } collection.Add(descriptor); return collection; } public static IServiceCollection RemoveAll(this IServiceCollection collection) { return collection.RemoveAll(typeof(T)); } public static IServiceCollection RemoveAll(this IServiceCollection collection, Type serviceType) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); for (int num = collection.Count - 1; num >= 0; num--) { ServiceDescriptor serviceDescriptor = collection[num]; if (serviceDescriptor.ServiceType == serviceType && serviceDescriptor.ServiceKey == null) { collection.RemoveAt(num); } } return collection; } public static void TryAddKeyedTransient(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service, object? serviceKey) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedTransient(service, serviceKey, service); collection.TryAdd(descriptor); } public static void TryAddKeyedTransient(this IServiceCollection collection, Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedTransient(service, serviceKey, implementationType); collection.TryAdd(descriptor); } public static void TryAddKeyedTransient(this IServiceCollection collection, Type service, object? serviceKey, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedTransient(service, serviceKey, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddKeyedTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection, object? serviceKey) where TService : class { ExceptionPolyfills.ThrowIfNull(collection, "collection"); collection.TryAddKeyedTransient(typeof(TService), serviceKey, typeof(TService)); } public static void TryAddKeyedTransient(this IServiceCollection collection, object? serviceKey) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(collection, "collection"); collection.TryAddKeyedTransient(typeof(TService), serviceKey, typeof(TImplementation)); } public static void TryAddKeyedTransient(this IServiceCollection services, object? serviceKey, Func implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.KeyedTransient(serviceKey, implementationFactory)); } public static void TryAddKeyedScoped(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service, object? serviceKey) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedScoped(service, serviceKey, service); collection.TryAdd(descriptor); } public static void TryAddKeyedScoped(this IServiceCollection collection, Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedScoped(service, serviceKey, implementationType); collection.TryAdd(descriptor); } public static void TryAddKeyedScoped(this IServiceCollection collection, Type service, object? serviceKey, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedScoped(service, serviceKey, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddKeyedScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection, object? serviceKey) where TService : class { ExceptionPolyfills.ThrowIfNull(collection, "collection"); collection.TryAddKeyedScoped(typeof(TService), serviceKey, typeof(TService)); } public static void TryAddKeyedScoped(this IServiceCollection collection, object? serviceKey) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(collection, "collection"); collection.TryAddKeyedScoped(typeof(TService), serviceKey, typeof(TImplementation)); } public static void TryAddKeyedScoped(this IServiceCollection services, object? serviceKey, Func implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.KeyedScoped(serviceKey, implementationFactory)); } public static void TryAddKeyedSingleton(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service, object? serviceKey) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedSingleton(service, serviceKey, service); collection.TryAdd(descriptor); } public static void TryAddKeyedSingleton(this IServiceCollection collection, Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedSingleton(service, serviceKey, implementationType); collection.TryAdd(descriptor); } public static void TryAddKeyedSingleton(this IServiceCollection collection, Type service, object? serviceKey, Func implementationFactory) { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(service, "service"); ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedSingleton(service, serviceKey, implementationFactory); collection.TryAdd(descriptor); } public static void TryAddKeyedSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection, object? serviceKey) where TService : class { ExceptionPolyfills.ThrowIfNull(collection, "collection"); collection.TryAddKeyedSingleton(typeof(TService), serviceKey, typeof(TService)); } public static void TryAddKeyedSingleton(this IServiceCollection collection, object? serviceKey) where TService : class where TImplementation : class, TService { ExceptionPolyfills.ThrowIfNull(collection, "collection"); collection.TryAddKeyedSingleton(typeof(TService), serviceKey, typeof(TImplementation)); } public static void TryAddKeyedSingleton(this IServiceCollection collection, object? serviceKey, TService instance) where TService : class { ExceptionPolyfills.ThrowIfNull(collection, "collection"); ExceptionPolyfills.ThrowIfNull(instance, "instance"); ServiceDescriptor descriptor = ServiceDescriptor.KeyedSingleton(typeof(TService), serviceKey, instance); collection.TryAdd(descriptor); } public static void TryAddKeyedSingleton(this IServiceCollection services, object? serviceKey, Func implementationFactory) where TService : class { services.TryAdd(ServiceDescriptor.KeyedSingleton(serviceKey, implementationFactory)); } public static IServiceCollection RemoveAllKeyed(this IServiceCollection collection, object? serviceKey) { return collection.RemoveAllKeyed(typeof(T), serviceKey); } public static IServiceCollection RemoveAllKeyed(this IServiceCollection collection, Type serviceType, object? serviceKey) { ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType"); for (int num = collection.Count - 1; num >= 0; num--) { ServiceDescriptor serviceDescriptor = collection[num]; if (serviceDescriptor.ServiceType == serviceType && object.Equals(serviceDescriptor.ServiceKey, serviceKey)) { collection.RemoveAt(num); } } return collection; } } }