diff --git a/src/libraries/Common/src/Extensions/ActivatorUtilities/ActivatorUtilities.cs b/src/libraries/Common/src/Extensions/ActivatorUtilities/ActivatorUtilities.cs new file mode 100644 index 00000000000..e2553ced1a2 --- /dev/null +++ b/src/libraries/Common/src/Extensions/ActivatorUtilities/ActivatorUtilities.cs @@ -0,0 +1,429 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.ExceptionServices; + +#if ActivatorUtilities_In_DependencyInjection +using Microsoft.Extensions.Internal; + +namespace Microsoft.Extensions.DependencyInjection +#else +namespace Microsoft.Extensions.Internal +#endif +{ + /// + /// Helper code for the various activator services. + /// + +#if ActivatorUtilities_In_DependencyInjection + public +#else + // Do not take a dependency on this class unless you are explicitly trying to avoid taking a + // dependency on Microsoft.AspNetCore.DependencyInjection.Abstractions. + internal +#endif + static class ActivatorUtilities + { + private static readonly MethodInfo GetServiceInfo = + GetMethodInfo>((sp, t, r, c) => GetService(sp, t, r, c)); + + /// + /// Instantiate a type with constructor arguments provided directly and/or from an . + /// + /// The service provider used to resolve dependencies + /// The type to activate + /// Constructor arguments not provided by the . + /// An activated object of type instanceType + public static object CreateInstance(IServiceProvider provider, Type instanceType, params object[] parameters) + { + int bestLength = -1; + var seenPreferred = false; + + ConstructorMatcher bestMatcher = null; + + if (!instanceType.GetTypeInfo().IsAbstract) + { + foreach (var constructor in instanceType + .GetTypeInfo() + .DeclaredConstructors + .Where(c => !c.IsStatic && c.IsPublic)) + { + var matcher = new ConstructorMatcher(constructor); + var isPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false); + var length = matcher.Match(parameters); + + if (isPreferred) + { + if (seenPreferred) + { + ThrowMultipleCtorsMarkedWithAttributeException(); + } + + if (length == -1) + { + ThrowMarkedCtorDoesNotTakeAllProvidedArguments(); + } + } + + if (isPreferred || bestLength < length) + { + bestLength = length; + bestMatcher = matcher; + } + + seenPreferred |= isPreferred; + } + } + + if (bestMatcher == null) + { + var message = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor."; + throw new InvalidOperationException(message); + } + + return bestMatcher.CreateInstance(provider); + } + + /// + /// Create a delegate that will instantiate a type with constructor arguments provided directly + /// and/or from an . + /// + /// The type to activate + /// + /// The types of objects, in order, that will be passed to the returned function as its second parameter + /// + /// + /// A factory that will instantiate instanceType using an + /// and an argument array containing objects matching the types defined in argumentTypes + /// + public static ObjectFactory CreateFactory(Type instanceType, Type[] argumentTypes) + { + FindApplicableConstructor(instanceType, argumentTypes, out ConstructorInfo constructor, out int?[] parameterMap); + + var provider = Expression.Parameter(typeof(IServiceProvider), "provider"); + var argumentArray = Expression.Parameter(typeof(object[]), "argumentArray"); + var factoryExpressionBody = BuildFactoryExpression(constructor, parameterMap, provider, argumentArray); + + var factoryLamda = Expression.Lambda>( + factoryExpressionBody, provider, argumentArray); + + var result = factoryLamda.Compile(); + return result.Invoke; + } + + /// + /// Instantiate a type with constructor arguments provided directly and/or from an . + /// + /// The type to activate + /// The service provider used to resolve dependencies + /// Constructor arguments not provided by the . + /// An activated object of type T + public static T CreateInstance(IServiceProvider provider, params object[] parameters) + { + return (T)CreateInstance(provider, typeof(T), parameters); + } + + + /// + /// Retrieve an instance of the given type from the service provider. If one is not found then instantiate it directly. + /// + /// The type of the service + /// The service provider used to resolve dependencies + /// The resolved service or created instance + public static T GetServiceOrCreateInstance(IServiceProvider provider) + { + return (T)GetServiceOrCreateInstance(provider, typeof(T)); + } + + /// + /// Retrieve an instance of the given type from the service provider. If one is not found then instantiate it directly. + /// + /// The service provider + /// The type of the service + /// The resolved service or created instance + public static object GetServiceOrCreateInstance(IServiceProvider provider, Type type) + { + return provider.GetService(type) ?? CreateInstance(provider, type); + } + + private static MethodInfo GetMethodInfo(Expression expr) + { + var mc = (MethodCallExpression)expr.Body; + return mc.Method; + } + + private static object GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired) + { + var service = sp.GetService(type); + if (service == null && !isDefaultParameterRequired) + { + var message = $"Unable to resolve service for type '{type}' while attempting to activate '{requiredBy}'."; + throw new InvalidOperationException(message); + } + return service; + } + + private static Expression BuildFactoryExpression( + ConstructorInfo constructor, + int?[] parameterMap, + Expression serviceProvider, + Expression factoryArgumentArray) + { + var constructorParameters = constructor.GetParameters(); + var constructorArguments = new Expression[constructorParameters.Length]; + + for (var i = 0; i < constructorParameters.Length; i++) + { + var constructorParameter = constructorParameters[i]; + var parameterType = constructorParameter.ParameterType; + var hasDefaultValue = ParameterDefaultValue.TryGetDefaultValue(constructorParameter, out var defaultValue); + + if (parameterMap[i] != null) + { + constructorArguments[i] = Expression.ArrayAccess(factoryArgumentArray, Expression.Constant(parameterMap[i])); + } + else + { + var parameterTypeExpression = new Expression[] { serviceProvider, + Expression.Constant(parameterType, typeof(Type)), + Expression.Constant(constructor.DeclaringType, typeof(Type)), + Expression.Constant(hasDefaultValue) }; + constructorArguments[i] = Expression.Call(GetServiceInfo, parameterTypeExpression); + } + + // Support optional constructor arguments by passing in the default value + // when the argument would otherwise be null. + if (hasDefaultValue) + { + var defaultValueExpression = Expression.Constant(defaultValue); + constructorArguments[i] = Expression.Coalesce(constructorArguments[i], defaultValueExpression); + } + + constructorArguments[i] = Expression.Convert(constructorArguments[i], parameterType); + } + + return Expression.New(constructor, constructorArguments); + } + + private static void FindApplicableConstructor( + Type instanceType, + Type[] argumentTypes, + out ConstructorInfo matchingConstructor, + out int?[] parameterMap) + { + matchingConstructor = null; + parameterMap = null; + + if (!TryFindPreferredConstructor(instanceType, argumentTypes, ref matchingConstructor, ref parameterMap) && + !TryFindMatchingConstructor(instanceType, argumentTypes, ref matchingConstructor, ref parameterMap)) + { + var message = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor."; + throw new InvalidOperationException(message); + } + } + + // Tries to find constructor based on provided argument types + private static bool TryFindMatchingConstructor( + Type instanceType, + Type[] argumentTypes, + ref ConstructorInfo matchingConstructor, + ref int?[] parameterMap) + { + foreach (var constructor in instanceType.GetTypeInfo().DeclaredConstructors) + { + if (constructor.IsStatic || !constructor.IsPublic) + { + continue; + } + + if (TryCreateParameterMap(constructor.GetParameters(), argumentTypes, out int?[] tempParameterMap)) + { + if (matchingConstructor != null) + { + throw new InvalidOperationException($"Multiple constructors accepting all given argument types have been found in type '{instanceType}'. There should only be one applicable constructor."); + } + + matchingConstructor = constructor; + parameterMap = tempParameterMap; + } + } + + return matchingConstructor != null; + } + + // Tries to find constructor marked with ActivatorUtilitiesConstructorAttribute + private static bool TryFindPreferredConstructor( + Type instanceType, + Type[] argumentTypes, + ref ConstructorInfo matchingConstructor, + ref int?[] parameterMap) + { + var seenPreferred = false; + foreach (var constructor in instanceType.GetTypeInfo().DeclaredConstructors) + { + if (constructor.IsStatic || !constructor.IsPublic) + { + continue; + } + + if (constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false)) + { + if (seenPreferred) + { + ThrowMultipleCtorsMarkedWithAttributeException(); + } + + if (!TryCreateParameterMap(constructor.GetParameters(), argumentTypes, out int?[] tempParameterMap)) + { + ThrowMarkedCtorDoesNotTakeAllProvidedArguments(); + } + + matchingConstructor = constructor; + parameterMap = tempParameterMap; + seenPreferred = true; + } + } + + return matchingConstructor != null; + } + + // Creates an injective parameterMap from givenParameterTypes to assignable constructorParameters. + // Returns true if each given parameter type is assignable to a unique; otherwise, false. + private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters, Type[] argumentTypes, out int?[] parameterMap) + { + parameterMap = new int?[constructorParameters.Length]; + + for (var i = 0; i < argumentTypes.Length; i++) + { + var foundMatch = false; + var givenParameter = argumentTypes[i].GetTypeInfo(); + + for (var j = 0; j < constructorParameters.Length; j++) + { + if (parameterMap[j] != null) + { + // This ctor parameter has already been matched + continue; + } + + if (constructorParameters[j].ParameterType.GetTypeInfo().IsAssignableFrom(givenParameter)) + { + foundMatch = true; + parameterMap[j] = i; + break; + } + } + + if (!foundMatch) + { + return false; + } + } + + return true; + } + + private class ConstructorMatcher + { + private readonly ConstructorInfo _constructor; + private readonly ParameterInfo[] _parameters; + private readonly object[] _parameterValues; + private readonly bool[] _parameterValuesSet; + + public ConstructorMatcher(ConstructorInfo constructor) + { + _constructor = constructor; + _parameters = _constructor.GetParameters(); + _parameterValuesSet = new bool[_parameters.Length]; + _parameterValues = new object[_parameters.Length]; + } + + public int Match(object[] givenParameters) + { + var applyIndexStart = 0; + var applyExactLength = 0; + for (var givenIndex = 0; givenIndex != givenParameters.Length; givenIndex++) + { + var givenType = givenParameters[givenIndex]?.GetType().GetTypeInfo(); + var givenMatched = false; + + for (var applyIndex = applyIndexStart; givenMatched == false && applyIndex != _parameters.Length; ++applyIndex) + { + if (_parameterValuesSet[applyIndex] == false && + _parameters[applyIndex].ParameterType.GetTypeInfo().IsAssignableFrom(givenType)) + { + givenMatched = true; + _parameterValuesSet[applyIndex] = true; + _parameterValues[applyIndex] = givenParameters[givenIndex]; + if (applyIndexStart == applyIndex) + { + applyIndexStart++; + if (applyIndex == givenIndex) + { + applyExactLength = applyIndex; + } + } + } + } + + if (givenMatched == false) + { + return -1; + } + } + return applyExactLength; + } + + public object CreateInstance(IServiceProvider provider) + { + for (var index = 0; index != _parameters.Length; index++) + { + if (_parameterValuesSet[index] == false) + { + var value = provider.GetService(_parameters[index].ParameterType); + if (value == null) + { + if (!ParameterDefaultValue.TryGetDefaultValue(_parameters[index], out var defaultValue)) + { + throw new InvalidOperationException($"Unable to resolve service for type '{_parameters[index].ParameterType}' while attempting to activate '{_constructor.DeclaringType}'."); + } + else + { + _parameterValues[index] = defaultValue; + } + } + else + { + _parameterValues[index] = value; + } + } + } + + try + { + return _constructor.Invoke(_parameterValues); + } + catch (TargetInvocationException ex) + { + ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); + // The above line will always throw, but the compiler requires we throw explicitly. + throw; + } + } + } + + private static void ThrowMultipleCtorsMarkedWithAttributeException() + { + throw new InvalidOperationException($"Multiple constructors were marked with {nameof(ActivatorUtilitiesConstructorAttribute)}."); + } + + private static void ThrowMarkedCtorDoesNotTakeAllProvidedArguments() + { + throw new InvalidOperationException($"Constructor marked with {nameof(ActivatorUtilitiesConstructorAttribute)} does not accept all given argument types."); + } + } +} diff --git a/src/libraries/Common/src/Extensions/ActivatorUtilities/ActivatorUtilitiesConstructorAttribute.cs b/src/libraries/Common/src/Extensions/ActivatorUtilities/ActivatorUtilitiesConstructorAttribute.cs new file mode 100644 index 00000000000..67ffa13f6fc --- /dev/null +++ b/src/libraries/Common/src/Extensions/ActivatorUtilities/ActivatorUtilitiesConstructorAttribute.cs @@ -0,0 +1,26 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +#if ActivatorUtilities_In_DependencyInjection +namespace Microsoft.Extensions.DependencyInjection +#else +namespace Microsoft.Extensions.Internal +#endif +{ + /// + /// Marks the constructor to be used when activating type using . + /// + +#if ActivatorUtilities_In_DependencyInjection + public +#else + // Do not take a dependency on this class unless you are explicitly trying to avoid taking a + // dependency on Microsoft.AspNetCore.DependencyInjection.Abstractions. + internal +#endif + class ActivatorUtilitiesConstructorAttribute: Attribute + { + } +} diff --git a/src/libraries/Common/src/Extensions/ActivatorUtilities/ObjectFactory.cs b/src/libraries/Common/src/Extensions/ActivatorUtilities/ObjectFactory.cs new file mode 100644 index 00000000000..517247811ec --- /dev/null +++ b/src/libraries/Common/src/Extensions/ActivatorUtilities/ObjectFactory.cs @@ -0,0 +1,25 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +#if ActivatorUtilities_In_DependencyInjection +namespace Microsoft.Extensions.DependencyInjection +#else +namespace Microsoft.Extensions.Internal +#endif +{ + + /// + /// The result of . + /// + /// The to get service arguments from. + /// Additional constructor arguments. + /// The instantiated type. +#if ActivatorUtilities_In_DependencyInjection + public +#else + internal +#endif + delegate object ObjectFactory(IServiceProvider serviceProvider, object[] arguments); +} \ No newline at end of file diff --git a/src/libraries/Common/src/Extensions/ActivatorUtilities/sharedsources.props b/src/libraries/Common/src/Extensions/ActivatorUtilities/sharedsources.props new file mode 100644 index 00000000000..b35fe34b10f --- /dev/null +++ b/src/libraries/Common/src/Extensions/ActivatorUtilities/sharedsources.props @@ -0,0 +1,8 @@ + + + + true + $(ContentTargetFolders)\cs\netstandard1.0\ + + + diff --git a/src/libraries/Common/src/Extensions/ParameterDefaultValue/ParameterDefaultValue.cs b/src/libraries/Common/src/Extensions/ParameterDefaultValue/ParameterDefaultValue.cs new file mode 100644 index 00000000000..a71bad37b1a --- /dev/null +++ b/src/libraries/Common/src/Extensions/ParameterDefaultValue/ParameterDefaultValue.cs @@ -0,0 +1,47 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Reflection; + +namespace Microsoft.Extensions.Internal +{ + internal class ParameterDefaultValue + { + public static bool TryGetDefaultValue(ParameterInfo parameter, out object defaultValue) + { + bool hasDefaultValue; + var tryToGetDefaultValue = true; + defaultValue = null; + + try + { + hasDefaultValue = parameter.HasDefaultValue; + } + catch (FormatException) when (parameter.ParameterType == typeof(DateTime)) + { + // Workaround for https://github.com/dotnet/corefx/issues/12338 + // If HasDefaultValue throws FormatException for DateTime + // we expect it to have default value + hasDefaultValue = true; + tryToGetDefaultValue = false; + } + + if (hasDefaultValue) + { + if (tryToGetDefaultValue) + { + defaultValue = parameter.DefaultValue; + } + + // Workaround for https://github.com/dotnet/corefx/issues/11797 + if (defaultValue == null && parameter.ParameterType.IsValueType) + { + defaultValue = Activator.CreateInstance(parameter.ParameterType); + } + } + + return hasDefaultValue; + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.cs new file mode 100644 index 00000000000..300ded03ce5 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.cs @@ -0,0 +1,722 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.Extensions.DependencyInjection.Abstractions; + +namespace Microsoft.Extensions.DependencyInjection.Extensions +{ + /// + /// Extension methods for adding and removing services to an . + /// + public static class ServiceCollectionDescriptorExtensions + { + /// + /// Adds the specified to the . + /// + /// The . + /// The to add. + /// A reference to the current instance of . + public static IServiceCollection Add( + this IServiceCollection collection, + ServiceDescriptor descriptor) + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + if (descriptor == null) + { + throw new ArgumentNullException(nameof(descriptor)); + } + + collection.Add(descriptor); + return collection; + } + + /// + /// Adds a sequence of to the . + /// + /// The . + /// The s to add. + /// A reference to the current instance of . + public static IServiceCollection Add( + this IServiceCollection collection, + IEnumerable descriptors) + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + if (descriptors == null) + { + throw new ArgumentNullException(nameof(descriptors)); + } + + foreach (var descriptor in descriptors) + { + collection.Add(descriptor); + } + + return collection; + } + + /// + /// Adds the specified to the if the + /// service type hasn't already been registered. + /// + /// The . + /// The to add. + public static void TryAdd( + this IServiceCollection collection, + ServiceDescriptor descriptor) + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + if (descriptor == null) + { + throw new ArgumentNullException(nameof(descriptor)); + } + + if (!collection.Any(d => d.ServiceType == descriptor.ServiceType)) + { + collection.Add(descriptor); + } + } + + /// + /// Adds the specified to the if the + /// service type hasn't already been registered. + /// + /// The . + /// The s to add. + public static void TryAdd( + this IServiceCollection collection, + IEnumerable descriptors) + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + if (descriptors == null) + { + throw new ArgumentNullException(nameof(descriptors)); + } + + foreach (var d in descriptors) + { + collection.TryAdd(d); + } + } + + /// + /// Adds the specified as a service + /// to the if the service type hasn't already been registered. + /// + /// The . + /// The type of the service to register. + public static void TryAddTransient( + this IServiceCollection collection, + Type service) + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + if (service == null) + { + throw new ArgumentNullException(nameof(service)); + } + + var descriptor = ServiceDescriptor.Transient(service, service); + TryAdd(collection, descriptor); + } + + /// + /// Adds the specified as a service + /// with the implementation + /// to the if the service type hasn't already been registered. + /// + /// The . + /// The type of the service to register. + /// The implementation type of the service. + public static void TryAddTransient( + this IServiceCollection collection, + Type service, + Type implementationType) + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + if (service == null) + { + throw new ArgumentNullException(nameof(service)); + } + + if (implementationType == null) + { + throw new ArgumentNullException(nameof(implementationType)); + } + + var descriptor = ServiceDescriptor.Transient(service, implementationType); + TryAdd(collection, descriptor); + } + + /// + /// Adds the specified as a service + /// using the factory specified in + /// to the if the service type hasn't already been registered. + /// + /// The . + /// The type of the service to register. + /// The factory that creates the service. + public static void TryAddTransient( + this IServiceCollection collection, + Type service, + Func implementationFactory) + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + if (service == null) + { + throw new ArgumentNullException(nameof(service)); + } + + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + var descriptor = ServiceDescriptor.Transient(service, implementationFactory); + TryAdd(collection, descriptor); + } + + /// + /// Adds the specified as a service + /// to the if the service type hasn't already been registered. + /// + /// The type of the service to add. + /// The . + public static void TryAddTransient(this IServiceCollection collection) + where TService : class + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + TryAddTransient(collection, typeof(TService), typeof(TService)); + } + + /// + /// Adds the specified as a service + /// implementation type specified in + /// to the if the service type hasn't already been registered. + /// + /// The type of the service to add. + /// The type of the implementation to use. + /// The . + public static void TryAddTransient(this IServiceCollection collection) + where TService : class + where TImplementation : class, TService + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + TryAddTransient(collection, typeof(TService), typeof(TImplementation)); + } + + /// + /// Adds the specified as a service + /// using the factory specified in + /// to the if the service type hasn't already been registered. + /// + /// The type of the service to add. + /// The . + /// The factory that creates the service. + public static void TryAddTransient( + this IServiceCollection services, + Func implementationFactory) + where TService : class + { + services.TryAdd(ServiceDescriptor.Transient(implementationFactory)); + } + + /// + /// Adds the specified as a service + /// to the if the service type hasn't already been registered. + /// + /// The . + /// The type of the service to register. + public static void TryAddScoped( + this IServiceCollection collection, + Type service) + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + if (service == null) + { + throw new ArgumentNullException(nameof(service)); + } + + var descriptor = ServiceDescriptor.Scoped(service, service); + TryAdd(collection, descriptor); + } + + /// + /// Adds the specified as a service + /// with the implementation + /// to the if the service type hasn't already been registered. + /// + /// The . + /// The type of the service to register. + /// The implementation type of the service. + public static void TryAddScoped( + this IServiceCollection collection, + Type service, + Type implementationType) + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + if (service == null) + { + throw new ArgumentNullException(nameof(service)); + } + + if (implementationType == null) + { + throw new ArgumentNullException(nameof(implementationType)); + } + + var descriptor = ServiceDescriptor.Scoped(service, implementationType); + TryAdd(collection, descriptor); + } + + /// + /// Adds the specified as a service + /// using the factory specified in + /// to the if the service type hasn't already been registered. + /// + /// The . + /// The type of the service to register. + /// The factory that creates the service. + public static void TryAddScoped( + this IServiceCollection collection, + Type service, + Func implementationFactory) + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + if (service == null) + { + throw new ArgumentNullException(nameof(service)); + } + + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + var descriptor = ServiceDescriptor.Scoped(service, implementationFactory); + TryAdd(collection, descriptor); + } + + /// + /// Adds the specified as a service + /// to the if the service type hasn't already been registered. + /// + /// The type of the service to add. + /// The . + public static void TryAddScoped(this IServiceCollection collection) + where TService : class + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + TryAddScoped(collection, typeof(TService), typeof(TService)); + } + + /// + /// Adds the specified as a service + /// implementation type specified in + /// to the if the service type hasn't already been registered. + /// + /// The type of the service to add. + /// The type of the implementation to use. + /// The . + public static void TryAddScoped(this IServiceCollection collection) + where TService : class + where TImplementation : class, TService + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + TryAddScoped(collection, typeof(TService), typeof(TImplementation)); + } + + /// + /// Adds the specified as a service + /// using the factory specified in + /// to the if the service type hasn't already been registered. + /// + /// The type of the service to add. + /// The . + /// The factory that creates the service. + public static void TryAddScoped( + this IServiceCollection services, + Func implementationFactory) + where TService : class + { + services.TryAdd(ServiceDescriptor.Scoped(implementationFactory)); + } + + /// + /// Adds the specified as a service + /// to the if the service type hasn't already been registered. + /// + /// The . + /// The type of the service to register. + public static void TryAddSingleton( + this IServiceCollection collection, + Type service) + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + if (service == null) + { + throw new ArgumentNullException(nameof(service)); + } + + var descriptor = ServiceDescriptor.Singleton(service, service); + TryAdd(collection, descriptor); + } + + /// + /// Adds the specified as a service + /// with the implementation + /// to the if the service type hasn't already been registered. + /// + /// The . + /// The type of the service to register. + /// The implementation type of the service. + public static void TryAddSingleton( + this IServiceCollection collection, + Type service, + Type implementationType) + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + if (service == null) + { + throw new ArgumentNullException(nameof(service)); + } + + if (implementationType == null) + { + throw new ArgumentNullException(nameof(implementationType)); + } + + var descriptor = ServiceDescriptor.Singleton(service, implementationType); + TryAdd(collection, descriptor); + } + + /// + /// Adds the specified as a service + /// using the factory specified in + /// to the if the service type hasn't already been registered. + /// + /// The . + /// The type of the service to register. + /// The factory that creates the service. + public static void TryAddSingleton( + this IServiceCollection collection, + Type service, + Func implementationFactory) + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + if (service == null) + { + throw new ArgumentNullException(nameof(service)); + } + + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + var descriptor = ServiceDescriptor.Singleton(service, implementationFactory); + TryAdd(collection, descriptor); + } + + /// + /// Adds the specified as a service + /// to the if the service type hasn't already been registered. + /// + /// The type of the service to add. + /// The . + public static void TryAddSingleton(this IServiceCollection collection) + where TService : class + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + TryAddSingleton(collection, typeof(TService), typeof(TService)); + } + + /// + /// Adds the specified as a service + /// implementation type specified in + /// to the if the service type hasn't already been registered. + /// + /// The type of the service to add. + /// The type of the implementation to use. + /// The . + public static void TryAddSingleton(this IServiceCollection collection) + where TService : class + where TImplementation : class, TService + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + TryAddSingleton(collection, typeof(TService), typeof(TImplementation)); + } + + /// + /// Adds the specified as a service + /// with an instance specified in + /// to the if the service type hasn't already been registered. + /// + /// The type of the service to add. + /// The . + /// The instance of the service to add. + public static void TryAddSingleton(this IServiceCollection collection, TService instance) + where TService : class + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + if (instance == null) + { + throw new ArgumentNullException(nameof(instance)); + } + + var descriptor = ServiceDescriptor.Singleton(typeof(TService), instance); + TryAdd(collection, descriptor); + } + + /// + /// Adds the specified as a service + /// using the factory specified in + /// to the if the service type hasn't already been registered. + /// + /// The type of the service to add. + /// The . + /// The factory that creates the service. + public static void TryAddSingleton( + this IServiceCollection services, + Func implementationFactory) + where TService : class + { + services.TryAdd(ServiceDescriptor.Singleton(implementationFactory)); + } + + /// + /// Adds a if an existing descriptor with the same + /// and an implementation that does not already exist + /// in . + /// + /// The . + /// The . + /// + /// Use when registing a service implementation of a + /// service type that + /// supports multiple registrations of the same service type. Using + /// is not idempotent and can add + /// duplicate + /// instances if called twice. Using + /// will prevent registration + /// of multiple implementation types. + /// + public static void TryAddEnumerable( + this IServiceCollection services, + ServiceDescriptor descriptor) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (descriptor == null) + { + throw new ArgumentNullException(nameof(descriptor)); + } + + var implementationType = descriptor.GetImplementationType(); + + if (implementationType == typeof(object) || + implementationType == descriptor.ServiceType) + { + throw new ArgumentException( + Resources.FormatTryAddIndistinguishableTypeToEnumerable( + implementationType, + descriptor.ServiceType), + nameof(descriptor)); + } + + if (!services.Any(d => + d.ServiceType == descriptor.ServiceType && + d.GetImplementationType() == implementationType)) + { + services.Add(descriptor); + } + } + + /// + /// Adds the specified s if an existing descriptor with the same + /// and an implementation that does not already exist + /// in . + /// + /// The . + /// The s. + /// + /// Use when registing a service + /// implementation of a service type that + /// supports multiple registrations of the same service type. Using + /// is not idempotent and can add + /// duplicate + /// instances if called twice. Using + /// will prevent registration + /// of multiple implementation types. + /// + public static void TryAddEnumerable( + this IServiceCollection services, + IEnumerable descriptors) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (descriptors == null) + { + throw new ArgumentNullException(nameof(descriptors)); + } + + foreach (var d in descriptors) + { + services.TryAddEnumerable(d); + } + } + + /// + /// Removes the first service in with the same service type + /// as and adds to the collection. + /// + /// The . + /// The to replace with. + /// + public static IServiceCollection Replace( + this IServiceCollection collection, + ServiceDescriptor descriptor) + { + if (collection == null) + { + throw new ArgumentNullException(nameof(collection)); + } + + if (descriptor == null) + { + throw new ArgumentNullException(nameof(descriptor)); + } + + var registeredServiceDescriptor = collection.FirstOrDefault(s => s.ServiceType == descriptor.ServiceType); + if (registeredServiceDescriptor != null) + { + collection.Remove(registeredServiceDescriptor); + } + + collection.Add(descriptor); + return collection; + } + + /// + /// Removes all services of type in . + /// + /// The . + /// + public static IServiceCollection RemoveAll(this IServiceCollection collection) + { + return RemoveAll(collection, typeof(T)); + } + + /// + /// Removes all services of type in . + /// + /// The . + /// The service type to remove. + /// + public static IServiceCollection RemoveAll(this IServiceCollection collection, Type serviceType) + { + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + for (var i = collection.Count - 1; i >= 0; i--) + { + var descriptor = collection[i]; + if (descriptor.ServiceType == serviceType) + { + collection.RemoveAt(i); + } + } + + return collection; + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/IServiceCollection.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/IServiceCollection.cs new file mode 100644 index 00000000000..6caf01d3d88 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/IServiceCollection.cs @@ -0,0 +1,14 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Generic; + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// Specifies the contract for a collection of service descriptors. + /// + public interface IServiceCollection : IList + { + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/IServiceProviderFactory.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/IServiceProviderFactory.cs new file mode 100644 index 00000000000..ad01acdc7e2 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/IServiceProviderFactory.cs @@ -0,0 +1,24 @@ +using System; + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// Provides an extension point for creating a container specific builder and an . + /// + public interface IServiceProviderFactory + { + /// + /// Creates a container builder from an . + /// + /// The collection of services + /// A container builder that can be used to create an . + TContainerBuilder CreateBuilder(IServiceCollection services); + + /// + /// Creates an from the container builder. + /// + /// The container builder + /// An + IServiceProvider CreateServiceProvider(TContainerBuilder containerBuilder); + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/IServiceScope.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/IServiceScope.cs new file mode 100644 index 00000000000..4a6ee34be06 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/IServiceScope.cs @@ -0,0 +1,21 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// The method ends the scope lifetime. Once Dispose + /// is called, any scoped services that have been resolved from + /// will be + /// disposed. + /// + public interface IServiceScope : IDisposable + { + /// + /// The used to resolve dependencies from the scope. + /// + IServiceProvider ServiceProvider { get; } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/IServiceScopeFactory.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/IServiceScopeFactory.cs new file mode 100644 index 00000000000..0ec6ccd9313 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/IServiceScopeFactory.cs @@ -0,0 +1,25 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// A factory for creating instances of , which is used to create + /// services within a scope. + /// + public interface IServiceScopeFactory + { + /// + /// Create an which + /// contains an used to resolve dependencies from a + /// newly created scope. + /// + /// + /// An controlling the + /// lifetime of the scope. Once this is disposed, any scoped services that have been resolved + /// from the + /// will also be disposed. + /// + IServiceScope CreateScope(); + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ISupportRequiredService.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ISupportRequiredService.cs new file mode 100644 index 00000000000..3944d744555 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ISupportRequiredService.cs @@ -0,0 +1,23 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// Optional contract used by + /// to resolve services if supported by . + /// + public interface ISupportRequiredService + { + /// + /// Gets service of type from the implementing + /// this interface. + /// + /// An object that specifies the type of service object to get. + /// A service object of type . + /// Throws an exception if the cannot create the object. + object GetRequiredService(Type serviceType); + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Microsoft.Extensions.DependencyInjection.Abstractions.csproj b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Microsoft.Extensions.DependencyInjection.Abstractions.csproj new file mode 100644 index 00000000000..6f6ae0355b5 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Microsoft.Extensions.DependencyInjection.Abstractions.csproj @@ -0,0 +1,18 @@ + + + + Abstractions for dependency injection. +Commonly used types: +Microsoft.Extensions.DependencyInjection.IServiceCollection + netstandard2.0 + true + dependencyinjection;di + $(DefineConstants);ActivatorUtilities_In_DependencyInjection + + + + + + + + diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Properties/AssemblyInfo.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..7586e5bfdad --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Microsoft.Extensions.DependencyInjection.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Properties/Resources.Designer.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Properties/Resources.Designer.cs new file mode 100644 index 00000000000..63275d99823 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Properties/Resources.Designer.cs @@ -0,0 +1,114 @@ +// +namespace Microsoft.Extensions.DependencyInjection.Abstractions +{ + using System.Globalization; + using System.Reflection; + using System.Resources; + + internal static class Resources + { + private static readonly ResourceManager _resourceManager + = new ResourceManager("Microsoft.Extensions.DependencyInjection.Abstractions.Resources", typeof(Resources).GetTypeInfo().Assembly); + + /// + /// Multiple constructors accepting all given argument types have been found in type '{0}'. There should only be one applicable constructor. + /// + internal static string AmbiguousConstructorMatch + { + get => GetString("AmbiguousConstructorMatch"); + } + + /// + /// Multiple constructors accepting all given argument types have been found in type '{0}'. There should only be one applicable constructor. + /// + internal static string FormatAmbiguousConstructorMatch(object p0) + => string.Format(CultureInfo.CurrentCulture, GetString("AmbiguousConstructorMatch"), p0); + + /// + /// Unable to locate implementation '{0}' for service '{1}'. + /// + internal static string CannotLocateImplementation + { + get => GetString("CannotLocateImplementation"); + } + + /// + /// Unable to locate implementation '{0}' for service '{1}'. + /// + internal static string FormatCannotLocateImplementation(object p0, object p1) + => string.Format(CultureInfo.CurrentCulture, GetString("CannotLocateImplementation"), p0, p1); + + /// + /// Unable to resolve service for type '{0}' while attempting to activate '{1}'. + /// + internal static string CannotResolveService + { + get => GetString("CannotResolveService"); + } + + /// + /// Unable to resolve service for type '{0}' while attempting to activate '{1}'. + /// + internal static string FormatCannotResolveService(object p0, object p1) + => string.Format(CultureInfo.CurrentCulture, GetString("CannotResolveService"), p0, p1); + + /// + /// A suitable constructor for type '{0}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor. + /// + internal static string NoConstructorMatch + { + get => GetString("NoConstructorMatch"); + } + + /// + /// A suitable constructor for type '{0}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor. + /// + internal static string FormatNoConstructorMatch(object p0) + => string.Format(CultureInfo.CurrentCulture, GetString("NoConstructorMatch"), p0); + + /// + /// No service for type '{0}' has been registered. + /// + internal static string NoServiceRegistered + { + get => GetString("NoServiceRegistered"); + } + + /// + /// No service for type '{0}' has been registered. + /// + internal static string FormatNoServiceRegistered(object p0) + => string.Format(CultureInfo.CurrentCulture, GetString("NoServiceRegistered"), p0); + + /// + /// Implementation type cannot be '{0}' because it is indistinguishable from other services registered for '{1}'. + /// + internal static string TryAddIndistinguishableTypeToEnumerable + { + get => GetString("TryAddIndistinguishableTypeToEnumerable"); + } + + /// + /// Implementation type cannot be '{0}' because it is indistinguishable from other services registered for '{1}'. + /// + internal static string FormatTryAddIndistinguishableTypeToEnumerable(object p0, object p1) + => string.Format(CultureInfo.CurrentCulture, GetString("TryAddIndistinguishableTypeToEnumerable"), p0, p1); + + private static string GetString(string name, params string[] formatterNames) + { + var value = _resourceManager.GetString(name); + + System.Diagnostics.Debug.Assert(value != null); + + if (formatterNames != null) + { + for (var i = 0; i < formatterNames.Length; i++) + { + value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}"); + } + } + + return value; + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Resources.resx b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Resources.resx new file mode 100644 index 00000000000..9f74883c8e8 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Resources.resx @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Multiple constructors accepting all given argument types have been found in type '{0}'. There should only be one applicable constructor. + {0} = service type + + + Unable to locate implementation '{0}' for service '{1}'. + {0} = implementation type, {1} = service type + + + Unable to resolve service for type '{0}' while attempting to activate '{1}'. + {0} = service which cannot be resolved, {1} = service being activated + + + A suitable constructor for type '{0}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor. + {0} = service type + + + No service for type '{0}' has been registered. + {0} = service type + + + Implementation type cannot be '{0}' because it is indistinguishable from other services registered for '{1}'. + {0} = implementation type, {1} = service type + + \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs new file mode 100644 index 00000000000..a000b0c32ce --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs @@ -0,0 +1,673 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// Extension methods for adding services to an . + /// + public static class ServiceCollectionServiceExtensions + { + /// + /// Adds a transient service of the type specified in with an + /// implementation of the type specified in to the + /// specified . + /// + /// The to add the service to. + /// The type of the service to register. + /// The implementation type of the service. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddTransient( + this IServiceCollection services, + Type serviceType, + Type implementationType) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + if (implementationType == null) + { + throw new ArgumentNullException(nameof(implementationType)); + } + + return Add(services, serviceType, implementationType, ServiceLifetime.Transient); + } + + /// + /// Adds a transient service of the type specified in with a + /// factory specified in to the + /// specified . + /// + /// The to add the service to. + /// The type of the service to register. + /// The factory that creates the service. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddTransient( + this IServiceCollection services, + Type serviceType, + Func implementationFactory) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return Add(services, serviceType, implementationFactory, ServiceLifetime.Transient); + } + + /// + /// Adds a transient service of the type specified in with an + /// implementation type specified in to the + /// specified . + /// + /// The type of the service to add. + /// The type of the implementation to use. + /// The to add the service to. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddTransient(this IServiceCollection services) + where TService : class + where TImplementation : class, TService + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + return services.AddTransient(typeof(TService), typeof(TImplementation)); + } + + /// + /// Adds a transient service of the type specified in to the + /// specified . + /// + /// The to add the service to. + /// The type of the service to register and the implementation to use. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddTransient( + this IServiceCollection services, + Type serviceType) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + return services.AddTransient(serviceType, serviceType); + } + + /// + /// Adds a transient service of the type specified in to the + /// specified . + /// + /// The type of the service to add. + /// The to add the service to. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddTransient(this IServiceCollection services) + where TService : class + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + return services.AddTransient(typeof(TService)); + } + + /// + /// Adds a transient service of the type specified in with a + /// factory specified in to the + /// specified . + /// + /// The type of the service to add. + /// The to add the service to. + /// The factory that creates the service. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddTransient( + this IServiceCollection services, + Func implementationFactory) + where TService : class + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return services.AddTransient(typeof(TService), implementationFactory); + } + + /// + /// Adds a transient service of the type specified in with an + /// implementation type specified in using the + /// factory specified in to the + /// specified . + /// + /// The type of the service to add. + /// The type of the implementation to use. + /// The to add the service to. + /// The factory that creates the service. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddTransient( + this IServiceCollection services, + Func implementationFactory) + where TService : class + where TImplementation : class, TService + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return services.AddTransient(typeof(TService), implementationFactory); + } + + + + /// + /// Adds a scoped service of the type specified in with an + /// implementation of the type specified in to the + /// specified . + /// + /// The to add the service to. + /// The type of the service to register. + /// The implementation type of the service. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddScoped( + this IServiceCollection services, + Type serviceType, + Type implementationType) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + if (implementationType == null) + { + throw new ArgumentNullException(nameof(implementationType)); + } + + return Add(services, serviceType, implementationType, ServiceLifetime.Scoped); + } + + /// + /// Adds a scoped service of the type specified in with a + /// factory specified in to the + /// specified . + /// + /// The to add the service to. + /// The type of the service to register. + /// The factory that creates the service. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddScoped( + this IServiceCollection services, + Type serviceType, + Func implementationFactory) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return Add(services, serviceType, implementationFactory, ServiceLifetime.Scoped); + } + + /// + /// Adds a scoped service of the type specified in with an + /// implementation type specified in to the + /// specified . + /// + /// The type of the service to add. + /// The type of the implementation to use. + /// The to add the service to. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddScoped(this IServiceCollection services) + where TService : class + where TImplementation : class, TService + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + return services.AddScoped(typeof(TService), typeof(TImplementation)); + } + + /// + /// Adds a scoped service of the type specified in to the + /// specified . + /// + /// The to add the service to. + /// The type of the service to register and the implementation to use. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddScoped( + this IServiceCollection services, + Type serviceType) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + return services.AddScoped(serviceType, serviceType); + } + + /// + /// Adds a scoped service of the type specified in to the + /// specified . + /// + /// The type of the service to add. + /// The to add the service to. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddScoped(this IServiceCollection services) + where TService : class + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + return services.AddScoped(typeof(TService)); + } + + /// + /// Adds a scoped service of the type specified in with a + /// factory specified in to the + /// specified . + /// + /// The type of the service to add. + /// The to add the service to. + /// The factory that creates the service. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddScoped( + this IServiceCollection services, + Func implementationFactory) + where TService : class + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return services.AddScoped(typeof(TService), implementationFactory); + } + + /// + /// Adds a scoped service of the type specified in with an + /// implementation type specified in using the + /// factory specified in to the + /// specified . + /// + /// The type of the service to add. + /// The type of the implementation to use. + /// The to add the service to. + /// The factory that creates the service. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddScoped( + this IServiceCollection services, + Func implementationFactory) + where TService : class + where TImplementation : class, TService + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return services.AddScoped(typeof(TService), implementationFactory); + } + + + /// + /// Adds a singleton service of the type specified in with an + /// implementation of the type specified in to the + /// specified . + /// + /// The to add the service to. + /// The type of the service to register. + /// The implementation type of the service. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddSingleton( + this IServiceCollection services, + Type serviceType, + Type implementationType) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + if (implementationType == null) + { + throw new ArgumentNullException(nameof(implementationType)); + } + + return Add(services, serviceType, implementationType, ServiceLifetime.Singleton); + } + + /// + /// Adds a singleton service of the type specified in with a + /// factory specified in to the + /// specified . + /// + /// The to add the service to. + /// The type of the service to register. + /// The factory that creates the service. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddSingleton( + this IServiceCollection services, + Type serviceType, + Func implementationFactory) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return Add(services, serviceType, implementationFactory, ServiceLifetime.Singleton); + } + + /// + /// Adds a singleton service of the type specified in with an + /// implementation type specified in to the + /// specified . + /// + /// The type of the service to add. + /// The type of the implementation to use. + /// The to add the service to. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddSingleton(this IServiceCollection services) + where TService : class + where TImplementation : class, TService + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + return services.AddSingleton(typeof(TService), typeof(TImplementation)); + } + + /// + /// Adds a singleton service of the type specified in to the + /// specified . + /// + /// The to add the service to. + /// The type of the service to register and the implementation to use. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddSingleton( + this IServiceCollection services, + Type serviceType) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + return services.AddSingleton(serviceType, serviceType); + } + + /// + /// Adds a singleton service of the type specified in to the + /// specified . + /// + /// The type of the service to add. + /// The to add the service to. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddSingleton(this IServiceCollection services) + where TService : class + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + return services.AddSingleton(typeof(TService)); + } + + /// + /// Adds a singleton service of the type specified in with a + /// factory specified in to the + /// specified . + /// + /// The type of the service to add. + /// The to add the service to. + /// The factory that creates the service. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddSingleton( + this IServiceCollection services, + Func implementationFactory) + where TService : class + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return services.AddSingleton(typeof(TService), implementationFactory); + } + + /// + /// Adds a singleton service of the type specified in with an + /// implementation type specified in using the + /// factory specified in to the + /// specified . + /// + /// The type of the service to add. + /// The type of the implementation to use. + /// The to add the service to. + /// The factory that creates the service. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddSingleton( + this IServiceCollection services, + Func implementationFactory) + where TService : class + where TImplementation : class, TService + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return services.AddSingleton(typeof(TService), implementationFactory); + } + + /// + /// Adds a singleton service of the type specified in with an + /// instance specified in to the + /// specified . + /// + /// The to add the service to. + /// The type of the service to register. + /// The instance of the service. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddSingleton( + this IServiceCollection services, + Type serviceType, + object implementationInstance) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + if (implementationInstance == null) + { + throw new ArgumentNullException(nameof(implementationInstance)); + } + + var serviceDescriptor = new ServiceDescriptor(serviceType, implementationInstance); + services.Add(serviceDescriptor); + return services; + } + + /// + /// Adds a singleton service of the type specified in with an + /// instance specified in to the + /// specified . + /// + /// The to add the service to. + /// The instance of the service. + /// A reference to this instance after the operation has completed. + /// + public static IServiceCollection AddSingleton( + this IServiceCollection services, + TService implementationInstance) + where TService : class + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (implementationInstance == null) + { + throw new ArgumentNullException(nameof(implementationInstance)); + } + + return services.AddSingleton(typeof(TService), implementationInstance); + } + + private static IServiceCollection Add( + IServiceCollection collection, + Type serviceType, + Type implementationType, + ServiceLifetime lifetime) + { + var descriptor = new ServiceDescriptor(serviceType, implementationType, lifetime); + collection.Add(descriptor); + return collection; + } + + private static IServiceCollection Add( + IServiceCollection collection, + Type serviceType, + Func implementationFactory, + ServiceLifetime lifetime) + { + var descriptor = new ServiceDescriptor(serviceType, implementationFactory, lifetime); + collection.Add(descriptor); + return collection; + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs new file mode 100644 index 00000000000..5b1765756b6 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs @@ -0,0 +1,516 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Diagnostics; + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// Describes a service with its service type, implementation, and lifetime. + /// + [DebuggerDisplay("Lifetime = {Lifetime}, ServiceType = {ServiceType}, ImplementationType = {ImplementationType}")] + public class ServiceDescriptor + { + /// + /// Initializes a new instance of with the specified . + /// + /// The of the service. + /// The implementing the service. + /// The of the service. + public ServiceDescriptor( + Type serviceType, + Type implementationType, + ServiceLifetime lifetime) + : this(serviceType, lifetime) + { + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + if (implementationType == null) + { + throw new ArgumentNullException(nameof(implementationType)); + } + + ImplementationType = implementationType; + } + + /// + /// Initializes a new instance of with the specified + /// as a . + /// + /// The of the service. + /// The instance implementing the service. + public ServiceDescriptor( + Type serviceType, + object instance) + : this(serviceType, ServiceLifetime.Singleton) + { + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + if (instance == null) + { + throw new ArgumentNullException(nameof(instance)); + } + + ImplementationInstance = instance; + } + + /// + /// Initializes a new instance of with the specified . + /// + /// The of the service. + /// A factory used for creating service instances. + /// The of the service. + public ServiceDescriptor( + Type serviceType, + Func factory, + ServiceLifetime lifetime) + : this(serviceType, lifetime) + { + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + if (factory == null) + { + throw new ArgumentNullException(nameof(factory)); + } + + ImplementationFactory = factory; + } + + private ServiceDescriptor(Type serviceType, ServiceLifetime lifetime) + { + Lifetime = lifetime; + ServiceType = serviceType; + } + + /// + public ServiceLifetime Lifetime { get; } + + /// + public Type ServiceType { get; } + + /// + public Type ImplementationType { get; } + + /// + public object ImplementationInstance { get; } + + /// + public Func ImplementationFactory { get; } + + internal Type GetImplementationType() + { + if (ImplementationType != null) + { + return ImplementationType; + } + else if (ImplementationInstance != null) + { + return ImplementationInstance.GetType(); + } + else if (ImplementationFactory != null) + { + var typeArguments = ImplementationFactory.GetType().GenericTypeArguments; + + Debug.Assert(typeArguments.Length == 2); + + return typeArguments[1]; + } + + Debug.Assert(false, "ImplementationType, ImplementationInstance or ImplementationFactory must be non null"); + return null; + } + + /// + /// Creates an instance of with the specified + /// , , + /// and the lifetime. + /// + /// The type of the service. + /// The type of the implementation. + /// A new instance of . + public static ServiceDescriptor Transient() + where TService : class + where TImplementation : class, TService + { + return Describe(ServiceLifetime.Transient); + } + + /// + /// Creates an instance of with the specified + /// and + /// and the lifetime. + /// + /// The type of the service. + /// The type of the implementation. + /// A new instance of . + public static ServiceDescriptor Transient(Type service, Type implementationType) + { + if (service == null) + { + throw new ArgumentNullException(nameof(service)); + } + + if (implementationType == null) + { + throw new ArgumentNullException(nameof(implementationType)); + } + + return Describe(service, implementationType, ServiceLifetime.Transient); + } + + /// + /// Creates an instance of with the specified + /// , , + /// , + /// and the lifetime. + /// + /// The type of the service. + /// The type of the implementation. + /// A factory to create new instances of the service implementation. + /// A new instance of . + public static ServiceDescriptor Transient( + Func implementationFactory) + where TService : class + where TImplementation : class, TService + { + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); + } + + /// + /// Creates an instance of with the specified + /// , , + /// and the lifetime. + /// + /// The type of the service. + /// A factory to create new instances of the service implementation. + /// A new instance of . + public static ServiceDescriptor Transient(Func implementationFactory) + where TService : class + { + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); + } + + /// + /// Creates an instance of with the specified + /// , , + /// and the lifetime. + /// + /// The type of the service. + /// A factory to create new instances of the service implementation. + /// A new instance of . + public static ServiceDescriptor Transient(Type service, Func implementationFactory) + { + if (service == null) + { + throw new ArgumentNullException(nameof(service)); + } + + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return Describe(service, implementationFactory, ServiceLifetime.Transient); + } + + /// + /// Creates an instance of with the specified + /// , , + /// and the lifetime. + /// + /// The type of the service. + /// The type of the implementation. + /// A new instance of . + public static ServiceDescriptor Scoped() + where TService : class + where TImplementation : class, TService + { + return Describe(ServiceLifetime.Scoped); + } + + /// + /// Creates an instance of with the specified + /// and + /// and the lifetime. + /// + /// The type of the service. + /// The type of the implementation. + /// A new instance of . + public static ServiceDescriptor Scoped(Type service, Type implementationType) + { + return Describe(service, implementationType, ServiceLifetime.Scoped); + } + + /// + /// Creates an instance of with the specified + /// , , + /// , + /// and the lifetime. + /// + /// The type of the service. + /// The type of the implementation. + /// A factory to create new instances of the service implementation. + /// A new instance of . + public static ServiceDescriptor Scoped( + Func implementationFactory) + where TService : class + where TImplementation : class, TService + { + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); + } + + /// + /// Creates an instance of with the specified + /// , , + /// and the lifetime. + /// + /// The type of the service. + /// A factory to create new instances of the service implementation. + /// A new instance of . + public static ServiceDescriptor Scoped(Func implementationFactory) + where TService : class + { + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); + } + + /// + /// Creates an instance of with the specified + /// , , + /// and the lifetime. + /// + /// The type of the service. + /// A factory to create new instances of the service implementation. + /// A new instance of . + public static ServiceDescriptor Scoped(Type service, Func implementationFactory) + { + if (service == null) + { + throw new ArgumentNullException(nameof(service)); + } + + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return Describe(service, implementationFactory, ServiceLifetime.Scoped); + } + + /// + /// Creates an instance of with the specified + /// , , + /// and the lifetime. + /// + /// The type of the service. + /// The type of the implementation. + /// A new instance of . + public static ServiceDescriptor Singleton() + where TService : class + where TImplementation : class, TService + { + return Describe(ServiceLifetime.Singleton); + } + + /// + /// Creates an instance of with the specified + /// and + /// and the lifetime. + /// + /// The type of the service. + /// The type of the implementation. + /// A new instance of . + public static ServiceDescriptor Singleton(Type service, Type implementationType) + { + if (service == null) + { + throw new ArgumentNullException(nameof(service)); + } + + if (implementationType == null) + { + throw new ArgumentNullException(nameof(implementationType)); + } + + return Describe(service, implementationType, ServiceLifetime.Singleton); + } + + /// + /// Creates an instance of with the specified + /// , , + /// , + /// and the lifetime. + /// + /// The type of the service. + /// The type of the implementation. + /// A factory to create new instances of the service implementation. + /// A new instance of . + public static ServiceDescriptor Singleton( + Func implementationFactory) + where TService : class + where TImplementation : class, TService + { + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); + } + + /// + /// Creates an instance of with the specified + /// , , + /// and the lifetime. + /// + /// The type of the service. + /// A factory to create new instances of the service implementation. + /// A new instance of . + public static ServiceDescriptor Singleton(Func implementationFactory) + where TService : class + { + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); + } + + /// + /// Creates an instance of with the specified + /// , , + /// and the lifetime. + /// + /// The type of the service. + /// A factory to create new instances of the service implementation. + /// A new instance of . + public static ServiceDescriptor Singleton( + Type serviceType, + Func implementationFactory) + { + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + if (implementationFactory == null) + { + throw new ArgumentNullException(nameof(implementationFactory)); + } + + return Describe(serviceType, implementationFactory, ServiceLifetime.Singleton); + } + + /// + /// Creates an instance of with the specified + /// , , + /// and the lifetime. + /// + /// The type of the service. + /// The instance of the implementation. + /// A new instance of . + public static ServiceDescriptor Singleton(TService implementationInstance) + where TService : class + { + if (implementationInstance == null) + { + throw new ArgumentNullException(nameof(implementationInstance)); + } + + return Singleton(typeof(TService), implementationInstance); + } + + /// + /// Creates an instance of with the specified + /// , , + /// and the lifetime. + /// + /// The type of the service. + /// The instance of the implementation. + /// A new instance of . + public static ServiceDescriptor Singleton( + Type serviceType, + object implementationInstance) + { + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + if (implementationInstance == null) + { + throw new ArgumentNullException(nameof(implementationInstance)); + } + + return new ServiceDescriptor(serviceType, implementationInstance); + } + + private static ServiceDescriptor Describe(ServiceLifetime lifetime) + where TService : class + where TImplementation : class, TService + { + return Describe( + typeof(TService), + typeof(TImplementation), + lifetime: lifetime); + } + + /// + /// Creates an instance of with the specified + /// , , + /// and . + /// + /// The type of the service. + /// The type of the implementation. + /// The lifetime of the service. + /// A new instance of . + public static ServiceDescriptor Describe(Type serviceType, Type implementationType, ServiceLifetime lifetime) + { + return new ServiceDescriptor(serviceType, implementationType, lifetime); + } + + /// + /// Creates an instance of with the specified + /// , , + /// and . + /// + /// The type of the service. + /// A factory to create new instances of the service implementation. + /// The lifetime of the service. + /// A new instance of . + public static ServiceDescriptor Describe(Type serviceType, Func implementationFactory, ServiceLifetime lifetime) + { + return new ServiceDescriptor(serviceType, implementationFactory, lifetime); + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceLifetime.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceLifetime.cs new file mode 100644 index 00000000000..8606d578048 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceLifetime.cs @@ -0,0 +1,27 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// Specifies the lifetime of a service in an . + /// + public enum ServiceLifetime + { + /// + /// Specifies that a single instance of the service will be created. + /// + Singleton, + /// + /// Specifies that a new instance of the service will be created for each scope. + /// + /// + /// In ASP.NET Core applications a scope is created around each server request. + /// + Scoped, + /// + /// Specifies that a new instance of the service will be created every time it is requested. + /// + Transient + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderServiceExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderServiceExtensions.cs new file mode 100644 index 00000000000..86a0125a0d9 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderServiceExtensions.cs @@ -0,0 +1,130 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using Microsoft.Extensions.DependencyInjection.Abstractions; + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// Extension methods for getting services from an . + /// + public static class ServiceProviderServiceExtensions + { + /// + /// Get service of type from the . + /// + /// The type of service object to get. + /// The to retrieve the service object from. + /// A service object of type or null if there is no such service. + public static T GetService(this IServiceProvider provider) + { + if (provider == null) + { + throw new ArgumentNullException(nameof(provider)); + } + + return (T)provider.GetService(typeof(T)); + } + + /// + /// Get service of type from the . + /// + /// The to retrieve the service object from. + /// An object that specifies the type of service object to get. + /// A service object of type . + /// There is no service of type . + public static object GetRequiredService(this IServiceProvider provider, Type serviceType) + { + if (provider == null) + { + throw new ArgumentNullException(nameof(provider)); + } + + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + var requiredServiceSupportingProvider = provider as ISupportRequiredService; + if (requiredServiceSupportingProvider != null) + { + return requiredServiceSupportingProvider.GetRequiredService(serviceType); + } + + var service = provider.GetService(serviceType); + if (service == null) + { + throw new InvalidOperationException(Resources.FormatNoServiceRegistered(serviceType)); + } + + return service; + } + + /// + /// Get service of type from the . + /// + /// The type of service object to get. + /// The to retrieve the service object from. + /// A service object of type . + /// There is no service of type . + public static T GetRequiredService(this IServiceProvider provider) + { + if (provider == null) + { + throw new ArgumentNullException(nameof(provider)); + } + + return (T)provider.GetRequiredService(typeof(T)); + } + + /// + /// Get an enumeration of services of type from the . + /// + /// The type of service object to get. + /// The to retrieve the services from. + /// An enumeration of services of type . + public static IEnumerable GetServices(this IServiceProvider provider) + { + if (provider == null) + { + throw new ArgumentNullException(nameof(provider)); + } + + return provider.GetRequiredService>(); + } + + /// + /// Get an enumeration of services of type from the . + /// + /// The to retrieve the services from. + /// An object that specifies the type of service object to get. + /// An enumeration of services of type . + public static IEnumerable GetServices(this IServiceProvider provider, Type serviceType) + { + if (provider == null) + { + throw new ArgumentNullException(nameof(provider)); + } + + if (serviceType == null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + + var genericEnumerable = typeof(IEnumerable<>).MakeGenericType(serviceType); + return (IEnumerable)provider.GetRequiredService(genericEnumerable); + } + + /// + /// Creates a new that can be used to resolve scoped services. + /// + /// The to create the scope from. + /// A that can be used to resolve scoped services. + public static IServiceScope CreateScope(this IServiceProvider provider) + { + return provider.GetRequiredService().CreateScope(); + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/baseline.netcore.json b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/baseline.netcore.json new file mode 100644 index 00000000000..0f5314f182a --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/baseline.netcore.json @@ -0,0 +1,2253 @@ +{ + "AssemblyIdentity": "Microsoft.Extensions.DependencyInjection.Abstractions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60", + "Types": [ + { + "Name": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [ + "System.Collections.Generic.IList" + ], + "Members": [], + "GenericParameters": [] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.IServiceProviderFactory", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "CreateBuilder", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "T0", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "CreateServiceProvider", + "Parameters": [ + { + "Name": "containerBuilder", + "Type": "T0" + } + ], + "ReturnType": "System.IServiceProvider", + "GenericParameter": [] + } + ], + "GenericParameters": [ + { + "ParameterName": "TContainerBuilder", + "ParameterPosition": 0, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.IServiceScope", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [ + "System.IDisposable" + ], + "Members": [ + { + "Kind": "Method", + "Name": "get_ServiceProvider", + "Parameters": [], + "ReturnType": "System.IServiceProvider", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.IServiceScopeFactory", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "CreateScope", + "Parameters": [], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceScope", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.ISupportRequiredService", + "Visibility": "Public", + "Kind": "Interface", + "Abstract": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "GetRequiredService", + "Parameters": [ + { + "Name": "serviceType", + "Type": "System.Type" + } + ], + "ReturnType": "System.Object", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions", + "Visibility": "Public", + "Kind": "Class", + "Abstract": true, + "Static": true, + "Sealed": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "AddTransient", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "serviceType", + "Type": "System.Type" + }, + { + "Name": "implementationType", + "Type": "System.Type" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "AddTransient", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "serviceType", + "Type": "System.Type" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "AddTransient", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "New": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + }, + { + "ParameterName": "TImplementation", + "ParameterPosition": 1, + "Class": true, + "BaseTypeOrInterfaces": [ + "T0" + ] + } + ] + }, + { + "Kind": "Method", + "Name": "AddTransient", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "serviceType", + "Type": "System.Type" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "AddTransient", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "New": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "AddTransient", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "AddTransient", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + }, + { + "ParameterName": "TImplementation", + "ParameterPosition": 1, + "Class": true, + "BaseTypeOrInterfaces": [ + "T0" + ] + } + ] + }, + { + "Kind": "Method", + "Name": "AddScoped", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "serviceType", + "Type": "System.Type" + }, + { + "Name": "implementationType", + "Type": "System.Type" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "AddScoped", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "serviceType", + "Type": "System.Type" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "AddScoped", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "New": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + }, + { + "ParameterName": "TImplementation", + "ParameterPosition": 1, + "Class": true, + "BaseTypeOrInterfaces": [ + "T0" + ] + } + ] + }, + { + "Kind": "Method", + "Name": "AddScoped", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "serviceType", + "Type": "System.Type" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "AddScoped", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "New": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "AddScoped", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "AddScoped", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + }, + { + "ParameterName": "TImplementation", + "ParameterPosition": 1, + "Class": true, + "BaseTypeOrInterfaces": [ + "T0" + ] + } + ] + }, + { + "Kind": "Method", + "Name": "AddSingleton", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "serviceType", + "Type": "System.Type" + }, + { + "Name": "implementationType", + "Type": "System.Type" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "AddSingleton", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "serviceType", + "Type": "System.Type" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "AddSingleton", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "New": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + }, + { + "ParameterName": "TImplementation", + "ParameterPosition": 1, + "Class": true, + "BaseTypeOrInterfaces": [ + "T0" + ] + } + ] + }, + { + "Kind": "Method", + "Name": "AddSingleton", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "serviceType", + "Type": "System.Type" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "AddSingleton", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "New": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "AddSingleton", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "AddSingleton", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + }, + { + "ParameterName": "TImplementation", + "ParameterPosition": 1, + "Class": true, + "BaseTypeOrInterfaces": [ + "T0" + ] + } + ] + }, + { + "Kind": "Method", + "Name": "AddSingleton", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "serviceType", + "Type": "System.Type" + }, + { + "Name": "implementationInstance", + "Type": "System.Object" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "AddSingleton", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "implementationInstance", + "Type": "T0" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "get_Lifetime", + "Parameters": [], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceLifetime", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_ServiceType", + "Parameters": [], + "ReturnType": "System.Type", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_ImplementationType", + "Parameters": [], + "ReturnType": "System.Type", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_ImplementationInstance", + "Parameters": [], + "ReturnType": "System.Object", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_ImplementationFactory", + "Parameters": [], + "ReturnType": "System.Func", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Transient", + "Parameters": [], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + }, + { + "ParameterName": "TImplementation", + "ParameterPosition": 1, + "Class": true, + "BaseTypeOrInterfaces": [ + "T0" + ] + } + ] + }, + { + "Kind": "Method", + "Name": "Transient", + "Parameters": [ + { + "Name": "service", + "Type": "System.Type" + }, + { + "Name": "implementationType", + "Type": "System.Type" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Transient", + "Parameters": [ + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + }, + { + "ParameterName": "TImplementation", + "ParameterPosition": 1, + "Class": true, + "BaseTypeOrInterfaces": [ + "T0" + ] + } + ] + }, + { + "Kind": "Method", + "Name": "Transient", + "Parameters": [ + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "Transient", + "Parameters": [ + { + "Name": "service", + "Type": "System.Type" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Scoped", + "Parameters": [], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + }, + { + "ParameterName": "TImplementation", + "ParameterPosition": 1, + "Class": true, + "BaseTypeOrInterfaces": [ + "T0" + ] + } + ] + }, + { + "Kind": "Method", + "Name": "Scoped", + "Parameters": [ + { + "Name": "service", + "Type": "System.Type" + }, + { + "Name": "implementationType", + "Type": "System.Type" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Scoped", + "Parameters": [ + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + }, + { + "ParameterName": "TImplementation", + "ParameterPosition": 1, + "Class": true, + "BaseTypeOrInterfaces": [ + "T0" + ] + } + ] + }, + { + "Kind": "Method", + "Name": "Scoped", + "Parameters": [ + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "Scoped", + "Parameters": [ + { + "Name": "service", + "Type": "System.Type" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Singleton", + "Parameters": [], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + }, + { + "ParameterName": "TImplementation", + "ParameterPosition": 1, + "Class": true, + "BaseTypeOrInterfaces": [ + "T0" + ] + } + ] + }, + { + "Kind": "Method", + "Name": "Singleton", + "Parameters": [ + { + "Name": "service", + "Type": "System.Type" + }, + { + "Name": "implementationType", + "Type": "System.Type" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Singleton", + "Parameters": [ + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + }, + { + "ParameterName": "TImplementation", + "ParameterPosition": 1, + "Class": true, + "BaseTypeOrInterfaces": [ + "T0" + ] + } + ] + }, + { + "Kind": "Method", + "Name": "Singleton", + "Parameters": [ + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "Singleton", + "Parameters": [ + { + "Name": "serviceType", + "Type": "System.Type" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Singleton", + "Parameters": [ + { + "Name": "implementationInstance", + "Type": "T0" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "Singleton", + "Parameters": [ + { + "Name": "serviceType", + "Type": "System.Type" + }, + { + "Name": "implementationInstance", + "Type": "System.Object" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Describe", + "Parameters": [ + { + "Name": "serviceType", + "Type": "System.Type" + }, + { + "Name": "implementationType", + "Type": "System.Type" + }, + { + "Name": "lifetime", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceLifetime" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Describe", + "Parameters": [ + { + "Name": "serviceType", + "Type": "System.Type" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + }, + { + "Name": "lifetime", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceLifetime" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "serviceType", + "Type": "System.Type" + }, + { + "Name": "implementationType", + "Type": "System.Type" + }, + { + "Name": "lifetime", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceLifetime" + } + ], + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "serviceType", + "Type": "System.Type" + }, + { + "Name": "instance", + "Type": "System.Object" + } + ], + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "serviceType", + "Type": "System.Type" + }, + { + "Name": "factory", + "Type": "System.Func" + }, + { + "Name": "lifetime", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceLifetime" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.ServiceLifetime", + "Visibility": "Public", + "Kind": "Enumeration", + "Sealed": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Field", + "Name": "Singleton", + "Parameters": [], + "GenericParameter": [], + "Literal": "0" + }, + { + "Kind": "Field", + "Name": "Scoped", + "Parameters": [], + "GenericParameter": [], + "Literal": "1" + }, + { + "Kind": "Field", + "Name": "Transient", + "Parameters": [], + "GenericParameter": [], + "Literal": "2" + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions", + "Visibility": "Public", + "Kind": "Class", + "Abstract": true, + "Static": true, + "Sealed": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "GetService", + "Parameters": [ + { + "Name": "provider", + "Type": "System.IServiceProvider" + } + ], + "ReturnType": "T0", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "T", + "ParameterPosition": 0, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "GetRequiredService", + "Parameters": [ + { + "Name": "provider", + "Type": "System.IServiceProvider" + }, + { + "Name": "serviceType", + "Type": "System.Type" + } + ], + "ReturnType": "System.Object", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetRequiredService", + "Parameters": [ + { + "Name": "provider", + "Type": "System.IServiceProvider" + } + ], + "ReturnType": "T0", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "T", + "ParameterPosition": 0, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "GetServices", + "Parameters": [ + { + "Name": "provider", + "Type": "System.IServiceProvider" + } + ], + "ReturnType": "System.Collections.Generic.IEnumerable", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "T", + "ParameterPosition": 0, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "GetServices", + "Parameters": [ + { + "Name": "provider", + "Type": "System.IServiceProvider" + }, + { + "Name": "serviceType", + "Type": "System.Type" + } + ], + "ReturnType": "System.Collections.Generic.IEnumerable", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "CreateScope", + "Parameters": [ + { + "Name": "provider", + "Type": "System.IServiceProvider" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceScope", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.ActivatorUtilities", + "Visibility": "Public", + "Kind": "Class", + "Abstract": true, + "Static": true, + "Sealed": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "CreateInstance", + "Parameters": [ + { + "Name": "provider", + "Type": "System.IServiceProvider" + }, + { + "Name": "instanceType", + "Type": "System.Type" + }, + { + "Name": "parameters", + "Type": "System.Object[]", + "IsParams": true + } + ], + "ReturnType": "System.Object", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "CreateFactory", + "Parameters": [ + { + "Name": "instanceType", + "Type": "System.Type" + }, + { + "Name": "argumentTypes", + "Type": "System.Type[]" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ObjectFactory", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "CreateInstance", + "Parameters": [ + { + "Name": "provider", + "Type": "System.IServiceProvider" + }, + { + "Name": "parameters", + "Type": "System.Object[]", + "IsParams": true + } + ], + "ReturnType": "T0", + "Static": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "T", + "ParameterPosition": 0, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "GetServiceOrCreateInstance", + "Parameters": [ + { + "Name": "provider", + "Type": "System.IServiceProvider" + } + ], + "ReturnType": "T0", + "Static": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "T", + "ParameterPosition": 0, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "GetServiceOrCreateInstance", + "Parameters": [ + { + "Name": "provider", + "Type": "System.IServiceProvider" + }, + { + "Name": "type", + "Type": "System.Type" + } + ], + "ReturnType": "System.Object", + "Static": true, + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.ActivatorUtilitiesConstructorAttribute", + "Visibility": "Public", + "Kind": "Class", + "BaseType": "System.Attribute", + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.ObjectFactory", + "Visibility": "Public", + "Kind": "Class", + "Sealed": true, + "BaseType": "System.MulticastDelegate", + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "Invoke", + "Parameters": [ + { + "Name": "serviceProvider", + "Type": "System.IServiceProvider" + }, + { + "Name": "arguments", + "Type": "System.Object[]" + } + ], + "ReturnType": "System.Object", + "Virtual": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "BeginInvoke", + "Parameters": [ + { + "Name": "serviceProvider", + "Type": "System.IServiceProvider" + }, + { + "Name": "arguments", + "Type": "System.Object[]" + }, + { + "Name": "callback", + "Type": "System.AsyncCallback" + }, + { + "Name": "object", + "Type": "System.Object" + } + ], + "ReturnType": "System.IAsyncResult", + "Virtual": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "EndInvoke", + "Parameters": [ + { + "Name": "result", + "Type": "System.IAsyncResult" + } + ], + "ReturnType": "System.Object", + "Virtual": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "object", + "Type": "System.Object" + }, + { + "Name": "method", + "Type": "System.IntPtr" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions", + "Visibility": "Public", + "Kind": "Class", + "Abstract": true, + "Static": true, + "Sealed": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "Add", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "descriptor", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Add", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "descriptors", + "Type": "System.Collections.Generic.IEnumerable" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryAdd", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "descriptor", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryAdd", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "descriptors", + "Type": "System.Collections.Generic.IEnumerable" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryAddTransient", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "service", + "Type": "System.Type" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryAddTransient", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "service", + "Type": "System.Type" + }, + { + "Name": "implementationType", + "Type": "System.Type" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryAddTransient", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "service", + "Type": "System.Type" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryAddTransient", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "System.Void", + "Static": true, + "New": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "TryAddTransient", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "System.Void", + "Static": true, + "New": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + }, + { + "ParameterName": "TImplementation", + "ParameterPosition": 1, + "Class": true, + "BaseTypeOrInterfaces": [ + "T0" + ] + } + ] + }, + { + "Kind": "Method", + "Name": "TryAddTransient", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "TryAddScoped", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "service", + "Type": "System.Type" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryAddScoped", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "service", + "Type": "System.Type" + }, + { + "Name": "implementationType", + "Type": "System.Type" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryAddScoped", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "service", + "Type": "System.Type" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryAddScoped", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "System.Void", + "Static": true, + "New": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "TryAddScoped", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "System.Void", + "Static": true, + "New": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + }, + { + "ParameterName": "TImplementation", + "ParameterPosition": 1, + "Class": true, + "BaseTypeOrInterfaces": [ + "T0" + ] + } + ] + }, + { + "Kind": "Method", + "Name": "TryAddScoped", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "TryAddSingleton", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "service", + "Type": "System.Type" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryAddSingleton", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "service", + "Type": "System.Type" + }, + { + "Name": "implementationType", + "Type": "System.Type" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryAddSingleton", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "service", + "Type": "System.Type" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryAddSingleton", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "System.Void", + "Static": true, + "New": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "TryAddSingleton", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "System.Void", + "Static": true, + "New": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + }, + { + "ParameterName": "TImplementation", + "ParameterPosition": 1, + "Class": true, + "BaseTypeOrInterfaces": [ + "T0" + ] + } + ] + }, + { + "Kind": "Method", + "Name": "TryAddSingleton", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "instance", + "Type": "T0" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "TryAddSingleton", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "implementationFactory", + "Type": "System.Func" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "TService", + "ParameterPosition": 0, + "Class": true, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "TryAddEnumerable", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "descriptor", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "TryAddEnumerable", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "descriptors", + "Type": "System.Collections.Generic.IEnumerable" + } + ], + "ReturnType": "System.Void", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Replace", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "descriptor", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "RemoveAll", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [ + { + "ParameterName": "T", + "ParameterPosition": 0, + "BaseTypeOrInterfaces": [] + } + ] + }, + { + "Kind": "Method", + "Name": "RemoveAll", + "Parameters": [ + { + "Name": "collection", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "serviceType", + "Type": "System.Type" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + } + ] +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/DefaultServiceProviderFactory.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/DefaultServiceProviderFactory.cs new file mode 100644 index 00000000000..c1b902fb2a4 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/DefaultServiceProviderFactory.cs @@ -0,0 +1,49 @@ +using System; + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// Default implementation of . + /// + public class DefaultServiceProviderFactory : IServiceProviderFactory + { + private readonly ServiceProviderOptions _options; + + /// + /// Initializes a new instance of the class + /// with default options. + /// + /// + public DefaultServiceProviderFactory() : this(ServiceProviderOptions.Default) + { + + } + + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// The options to use for this instance. + public DefaultServiceProviderFactory(ServiceProviderOptions options) + { + if (options == null) + { + throw new ArgumentNullException(nameof(options)); + } + + _options = options; + } + + /// + public IServiceCollection CreateBuilder(IServiceCollection services) + { + return services; + } + + /// + public IServiceProvider CreateServiceProvider(IServiceCollection containerBuilder) + { + return containerBuilder.BuildServiceProvider(_options); + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/Microsoft.Extensions.DependencyInjection.csproj b/src/libraries/Microsoft.Extensions.DependencyInjection/src/Microsoft.Extensions.DependencyInjection.csproj new file mode 100644 index 00000000000..b8d680bfcad --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/Microsoft.Extensions.DependencyInjection.csproj @@ -0,0 +1,30 @@ + + + + Default implementation of dependency injection for Microsoft.Extensions.DependencyInjection. + netcoreapp2.0;net461;netstandard2.0 + true + dependencyinjection;di + + True + $(DefineConstants);IL_EMIT + + + False + $(DefineConstants);SAVE_ASSEMBLIES + + + + + + + + + + + + + + + + diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/Properties/AssemblyInfo.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..4afefbd651e --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/Properties/AssemblyInfo.cs @@ -0,0 +1,7 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Microsoft.Extensions.DependencyInjection.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] +[assembly: InternalsVisibleTo("Microsoft.Extensions.DependencyInjection.Performance, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/Properties/Resources.Designer.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/Properties/Resources.Designer.cs new file mode 100644 index 00000000000..7b3ce512730 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/Properties/Resources.Designer.cs @@ -0,0 +1,170 @@ +// +namespace Microsoft.Extensions.DependencyInjection +{ + using System.Globalization; + using System.Reflection; + using System.Resources; + + internal static class Resources + { + private static readonly ResourceManager _resourceManager + = new ResourceManager("Microsoft.Extensions.DependencyInjection.Resources", typeof(Resources).GetTypeInfo().Assembly); + + /// + /// Unable to activate type '{0}'. The following constructors are ambiguous: + /// + internal static string AmbiguousConstructorException + { + get => GetString("AmbiguousConstructorException"); + } + + /// + /// Unable to activate type '{0}'. The following constructors are ambiguous: + /// + internal static string FormatAmbiguousConstructorException(object p0) + => string.Format(CultureInfo.CurrentCulture, GetString("AmbiguousConstructorException"), p0); + + /// + /// Unable to resolve service for type '{0}' while attempting to activate '{1}'. + /// + internal static string CannotResolveService + { + get => GetString("CannotResolveService"); + } + + /// + /// Unable to resolve service for type '{0}' while attempting to activate '{1}'. + /// + internal static string FormatCannotResolveService(object p0, object p1) + => string.Format(CultureInfo.CurrentCulture, GetString("CannotResolveService"), p0, p1); + + /// + /// A circular dependency was detected for the service of type '{0}'. + /// + internal static string CircularDependencyException + { + get => GetString("CircularDependencyException"); + } + + /// + /// A circular dependency was detected for the service of type '{0}'. + /// + internal static string FormatCircularDependencyException(object p0) + => string.Format(CultureInfo.CurrentCulture, GetString("CircularDependencyException"), p0); + + /// + /// No constructor for type '{0}' can be instantiated using services from the service container and default values. + /// + internal static string UnableToActivateTypeException + { + get => GetString("UnableToActivateTypeException"); + } + + /// + /// No constructor for type '{0}' can be instantiated using services from the service container and default values. + /// + internal static string FormatUnableToActivateTypeException(object p0) + => string.Format(CultureInfo.CurrentCulture, GetString("UnableToActivateTypeException"), p0); + + /// + /// Open generic service type '{0}' requires registering an open generic implementation type. + /// + internal static string OpenGenericServiceRequiresOpenGenericImplementation + { + get => GetString("OpenGenericServiceRequiresOpenGenericImplementation"); + } + + /// + /// Open generic service type '{0}' requires registering an open generic implementation type. + /// + internal static string FormatOpenGenericServiceRequiresOpenGenericImplementation(object p0) + => string.Format(CultureInfo.CurrentCulture, GetString("OpenGenericServiceRequiresOpenGenericImplementation"), p0); + + /// + /// Cannot instantiate implementation type '{0}' for service type '{1}'. + /// + internal static string TypeCannotBeActivated + { + get => GetString("TypeCannotBeActivated"); + } + + /// + /// Cannot instantiate implementation type '{0}' for service type '{1}'. + /// + internal static string FormatTypeCannotBeActivated(object p0, object p1) + => string.Format(CultureInfo.CurrentCulture, GetString("TypeCannotBeActivated"), p0, p1); + + /// + /// A suitable constructor for type '{0}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor. + /// + internal static string NoConstructorMatch + { + get => GetString("NoConstructorMatch"); + } + + /// + /// A suitable constructor for type '{0}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor. + /// + internal static string FormatNoConstructorMatch(object p0) + => string.Format(CultureInfo.CurrentCulture, GetString("NoConstructorMatch"), p0); + + /// + /// Cannot consume {2} service '{0}' from {3} '{1}'. + /// + internal static string ScopedInSingletonException + { + get => GetString("ScopedInSingletonException"); + } + + /// + /// Cannot consume {2} service '{0}' from {3} '{1}'. + /// + internal static string FormatScopedInSingletonException(object p0, object p1, object p2, object p3) + => string.Format(CultureInfo.CurrentCulture, GetString("ScopedInSingletonException"), p0, p1, p2, p3); + + /// + /// Cannot resolve '{0}' from root provider because it requires {2} service '{1}'. + /// + internal static string ScopedResolvedFromRootException + { + get => GetString("ScopedResolvedFromRootException"); + } + + /// + /// Cannot resolve '{0}' from root provider because it requires {2} service '{1}'. + /// + internal static string FormatScopedResolvedFromRootException(object p0, object p1, object p2) + => string.Format(CultureInfo.CurrentCulture, GetString("ScopedResolvedFromRootException"), p0, p1, p2); + + /// + /// Cannot resolve {1} service '{0}' from root provider. + /// + internal static string DirectScopedResolvedFromRootException + { + get => GetString("DirectScopedResolvedFromRootException"); + } + + /// + /// Cannot resolve {1} service '{0}' from root provider. + /// + internal static string FormatDirectScopedResolvedFromRootException(object p0, object p1) + => string.Format(CultureInfo.CurrentCulture, GetString("DirectScopedResolvedFromRootException"), p0, p1); + + private static string GetString(string name, params string[] formatterNames) + { + var value = _resourceManager.GetString(name); + + System.Diagnostics.Debug.Assert(value != null); + + if (formatterNames != null) + { + for (var i = 0; i < formatterNames.Length; i++) + { + value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}"); + } + } + + return value; + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/Resources.resx b/src/libraries/Microsoft.Extensions.DependencyInjection/src/Resources.resx new file mode 100644 index 00000000000..4e90ca62210 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/Resources.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Unable to activate type '{0}'. The following constructors are ambiguous: + + + Unable to resolve service for type '{0}' while attempting to activate '{1}'. + {0} = service which cannot be resolved, {1} = service being activated + + + A circular dependency was detected for the service of type '{0}'. + {0} = service type with circular dependency + + + No constructor for type '{0}' can be instantiated using services from the service container and default values. + + + Open generic service type '{0}' requires registering an open generic implementation type. + + + Cannot instantiate implementation type '{0}' for service type '{1}'. + + + A suitable constructor for type '{0}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor. + {0} = service type + + + Cannot consume {2} service '{0}' from {3} '{1}'. + + + Cannot resolve '{0}' from root provider because it requires {2} service '{1}'. + + + Cannot resolve {1} service '{0}' from root provider. + + \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollection.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollection.cs new file mode 100644 index 00000000000..27b93ef126e --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollection.cs @@ -0,0 +1,93 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// Default implementation of . + /// + public class ServiceCollection : IServiceCollection + { + private readonly List _descriptors = new List(); + + /// + public int Count => _descriptors.Count; + + /// + public bool IsReadOnly => false; + + /// + public ServiceDescriptor this[int index] + { + get + { + return _descriptors[index]; + } + set + { + _descriptors[index] = value; + } + } + + /// + public void Clear() + { + _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) + { + return _descriptors.Remove(item); + } + + /// + public IEnumerator GetEnumerator() + { + return _descriptors.GetEnumerator(); + } + + void ICollection.Add(ServiceDescriptor item) + { + _descriptors.Add(item); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + /// + public int IndexOf(ServiceDescriptor item) + { + return _descriptors.IndexOf(item); + } + + /// + public void Insert(int index, ServiceDescriptor item) + { + _descriptors.Insert(index, item); + } + + /// + public void RemoveAt(int index) + { + _descriptors.RemoveAt(index); + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollectionContainerBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollectionContainerBuilderExtensions.cs new file mode 100644 index 00000000000..5e44a25c11f --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollectionContainerBuilderExtensions.cs @@ -0,0 +1,62 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// Extension methods for building a from an . + /// + public static class ServiceCollectionContainerBuilderExtensions + { + /// + /// Creates a containing services from the provided . + /// + /// The containing service descriptors. + /// The . + + public static ServiceProvider BuildServiceProvider(this IServiceCollection services) + { + return BuildServiceProvider(services, ServiceProviderOptions.Default); + } + + /// + /// Creates a containing services from the provided + /// optionaly enabling scope validation. + /// + /// The containing service descriptors. + /// + /// true to perform check verifying that scoped services never gets resolved from root provider; otherwise false. + /// + /// The . + public static ServiceProvider BuildServiceProvider(this IServiceCollection services, bool validateScopes) + { + return services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = validateScopes }); + } + + /// + /// Creates a containing services from the provided + /// optionaly enabling scope validation. + /// + /// The containing service descriptors. + /// + /// Configures various service provider behaviors. + /// + /// The . + public static ServiceProvider BuildServiceProvider(this IServiceCollection services, ServiceProviderOptions options) + { + if (services == null) + { + throw new ArgumentNullException(nameof(services)); + } + + if (options == null) + { + throw new ArgumentNullException(nameof(options)); + } + + return new ServiceProvider(services, options); + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteChain.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteChain.cs new file mode 100644 index 00000000000..562e887c70f --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteChain.cs @@ -0,0 +1,85 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Microsoft.Extensions.Internal; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class CallSiteChain + { + private readonly Dictionary _callSiteChain; + + public CallSiteChain() + { + _callSiteChain = new Dictionary(); + } + + public void CheckCircularDependency(Type serviceType) + { + if (_callSiteChain.ContainsKey(serviceType)) + { + throw new InvalidOperationException(CreateCircularDependencyExceptionMessage(serviceType)); + } + } + + public void Remove(Type serviceType) + { + _callSiteChain.Remove(serviceType); + } + + public void Add(Type serviceType, Type implementationType = null) + { + _callSiteChain[serviceType] = new ChainItemInfo(_callSiteChain.Count, implementationType); + } + + private string CreateCircularDependencyExceptionMessage(Type type) + { + var messageBuilder = new StringBuilder(); + messageBuilder.AppendFormat(Resources.CircularDependencyException, TypeNameHelper.GetTypeDisplayName(type)); + messageBuilder.AppendLine(); + + AppendResolutionPath(messageBuilder, type); + + return messageBuilder.ToString(); + } + + private void AppendResolutionPath(StringBuilder builder, Type currentlyResolving = null) + { + foreach (var pair in _callSiteChain.OrderBy(p => p.Value.Order)) + { + var serviceType = pair.Key; + var implementationType = pair.Value.ImplementationType; + if (implementationType == null || serviceType == implementationType) + { + builder.Append(TypeNameHelper.GetTypeDisplayName(serviceType)); + } + else + { + builder.AppendFormat("{0}({1})", + TypeNameHelper.GetTypeDisplayName(serviceType), + TypeNameHelper.GetTypeDisplayName(implementationType)); + } + + builder.Append(" -> "); + } + + builder.Append(TypeNameHelper.GetTypeDisplayName(currentlyResolving)); + } + + private struct ChainItemInfo + { + public int Order { get; } + public Type ImplementationType { get; } + + public ChainItemInfo(int order, Type implementationType) + { + Order = order; + ImplementationType = implementationType; + } + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteExpressionBuilderContext.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteExpressionBuilderContext.cs new file mode 100644 index 00000000000..fa0af251c93 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteExpressionBuilderContext.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Linq.Expressions; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class CallSiteExpressionBuilderContext + { + public ParameterExpression ScopeParameter { get; set; } + public bool RequiresResolvedServices { get; set; } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs new file mode 100644 index 00000000000..878b64b54e9 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs @@ -0,0 +1,435 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using Microsoft.Extensions.Internal; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class CallSiteFactory + { + private readonly List _descriptors; + private readonly Dictionary _callSiteCache = new Dictionary(); + private readonly Dictionary _descriptorLookup = new Dictionary(); + + public CallSiteFactory(IEnumerable descriptors) + { + _descriptors = descriptors.ToList(); + Populate(descriptors); + } + + private void Populate(IEnumerable descriptors) + { + foreach (var descriptor in descriptors) + { + var serviceTypeInfo = descriptor.ServiceType.GetTypeInfo(); + if (serviceTypeInfo.IsGenericTypeDefinition) + { + var implementationTypeInfo = descriptor.ImplementationType?.GetTypeInfo(); + + if (implementationTypeInfo == null || !implementationTypeInfo.IsGenericTypeDefinition) + { + throw new ArgumentException( + Resources.FormatOpenGenericServiceRequiresOpenGenericImplementation(descriptor.ServiceType), + nameof(descriptors)); + } + + if (implementationTypeInfo.IsAbstract || implementationTypeInfo.IsInterface) + { + throw new ArgumentException( + Resources.FormatTypeCannotBeActivated(descriptor.ImplementationType, descriptor.ServiceType)); + } + } + else if (descriptor.ImplementationInstance == null && descriptor.ImplementationFactory == null) + { + Debug.Assert(descriptor.ImplementationType != null); + var implementationTypeInfo = descriptor.ImplementationType.GetTypeInfo(); + + if (implementationTypeInfo.IsGenericTypeDefinition || + implementationTypeInfo.IsAbstract || + implementationTypeInfo.IsInterface) + { + throw new ArgumentException( + Resources.FormatTypeCannotBeActivated(descriptor.ImplementationType, descriptor.ServiceType)); + } + } + + var cacheKey = descriptor.ServiceType; + _descriptorLookup.TryGetValue(cacheKey, out var cacheItem); + _descriptorLookup[cacheKey] = cacheItem.Add(descriptor); + } + } + + internal IServiceCallSite CreateCallSite(Type serviceType, CallSiteChain callSiteChain) + { + lock (_callSiteCache) + { + if (_callSiteCache.TryGetValue(serviceType, out var cachedCallSite)) + { + return cachedCallSite; + } + + IServiceCallSite callSite; + try + { + callSiteChain.CheckCircularDependency(serviceType); + + callSite = TryCreateExact(serviceType, callSiteChain) ?? + TryCreateOpenGeneric(serviceType, callSiteChain) ?? + TryCreateEnumerable(serviceType, callSiteChain); + } + finally + { + callSiteChain.Remove(serviceType); + } + + _callSiteCache[serviceType] = callSite; + + return callSite; + } + } + + private IServiceCallSite TryCreateExact(Type serviceType, CallSiteChain callSiteChain) + { + if (_descriptorLookup.TryGetValue(serviceType, out var descriptor)) + { + return TryCreateExact(descriptor.Last, serviceType, callSiteChain); + } + + return null; + } + + private IServiceCallSite TryCreateOpenGeneric(Type serviceType, CallSiteChain callSiteChain) + { + if (serviceType.IsConstructedGenericType + && _descriptorLookup.TryGetValue(serviceType.GetGenericTypeDefinition(), out var descriptor)) + { + return TryCreateOpenGeneric(descriptor.Last, serviceType, callSiteChain); + } + + return null; + } + + private IServiceCallSite TryCreateEnumerable(Type serviceType, CallSiteChain callSiteChain) + { + if (serviceType.IsConstructedGenericType && + serviceType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) + { + var itemType = serviceType.GenericTypeArguments.Single(); + callSiteChain.Add(serviceType); + + var callSites = new List(); + + // If item type is not generic we can safely use descriptor cache + if (!itemType.IsConstructedGenericType && + _descriptorLookup.TryGetValue(itemType, out var descriptors)) + { + for (int i = 0; i < descriptors.Count; i++) + { + var descriptor = descriptors[i]; + + // There may not be any open generics here + var callSite = TryCreateExact(descriptor, itemType, callSiteChain); + Debug.Assert(callSite != null); + + callSites.Add(callSite); + } + } + else + { + foreach (var descriptor in _descriptors) + { + var callSite = TryCreateExact(descriptor, itemType, callSiteChain) ?? + TryCreateOpenGeneric(descriptor, itemType, callSiteChain); + + if (callSite != null) + { + callSites.Add(callSite); + } + } + + } + + return new IEnumerableCallSite(itemType, callSites.ToArray()); + } + + return null; + } + + private IServiceCallSite TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain) + { + if (serviceType == descriptor.ServiceType) + { + IServiceCallSite callSite; + if (descriptor.ImplementationInstance != null) + { + callSite = new ConstantCallSite(descriptor.ServiceType, descriptor.ImplementationInstance); + } + else if (descriptor.ImplementationFactory != null) + { + callSite = new FactoryCallSite(descriptor.ServiceType, descriptor.ImplementationFactory); + } + else if (descriptor.ImplementationType != null) + { + callSite = CreateConstructorCallSite(descriptor.ServiceType, descriptor.ImplementationType, callSiteChain); + } + else + { + throw new InvalidOperationException("Invalid service descriptor"); + } + + return ApplyLifetime(callSite, descriptor, descriptor.Lifetime); + } + + return null; + } + + private IServiceCallSite TryCreateOpenGeneric(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain) + { + if (serviceType.IsConstructedGenericType && + serviceType.GetGenericTypeDefinition() == descriptor.ServiceType) + { + Debug.Assert(descriptor.ImplementationType != null, "descriptor.ImplementationType != null"); + + var closedType = descriptor.ImplementationType.MakeGenericType(serviceType.GenericTypeArguments); + var constructorCallSite = CreateConstructorCallSite(serviceType, closedType, callSiteChain); + + return ApplyLifetime(constructorCallSite, Tuple.Create(descriptor, serviceType), descriptor.Lifetime); + } + + return null; + } + + private IServiceCallSite ApplyLifetime(IServiceCallSite serviceCallSite, object cacheKey, ServiceLifetime descriptorLifetime) + { + if (serviceCallSite is ConstantCallSite) + { + return serviceCallSite; + } + + switch (descriptorLifetime) + { + case ServiceLifetime.Transient: + return new TransientCallSite(serviceCallSite); + case ServiceLifetime.Scoped: + return new ScopedCallSite(serviceCallSite, cacheKey); + case ServiceLifetime.Singleton: + return new SingletonCallSite(serviceCallSite, cacheKey); + default: + throw new ArgumentOutOfRangeException(nameof(descriptorLifetime)); + } + } + + private IServiceCallSite CreateConstructorCallSite(Type serviceType, Type implementationType, CallSiteChain callSiteChain) + { + callSiteChain.Add(serviceType, implementationType); + + var constructors = implementationType.GetTypeInfo() + .DeclaredConstructors + .Where(constructor => constructor.IsPublic) + .ToArray(); + + IServiceCallSite[] parameterCallSites = null; + + if (constructors.Length == 0) + { + throw new InvalidOperationException(Resources.FormatNoConstructorMatch(implementationType)); + } + else if (constructors.Length == 1) + { + var constructor = constructors[0]; + var parameters = constructor.GetParameters(); + if (parameters.Length == 0) + { + return new CreateInstanceCallSite(serviceType, implementationType); + } + + parameterCallSites = CreateArgumentCallSites( + serviceType, + implementationType, + callSiteChain, + parameters, + throwIfCallSiteNotFound: true); + + return new ConstructorCallSite(serviceType, constructor, parameterCallSites); + } + + Array.Sort(constructors, + (a, b) => b.GetParameters().Length.CompareTo(a.GetParameters().Length)); + + ConstructorInfo bestConstructor = null; + HashSet bestConstructorParameterTypes = null; + for (var i = 0; i < constructors.Length; i++) + { + var parameters = constructors[i].GetParameters(); + + var currentParameterCallSites = CreateArgumentCallSites( + serviceType, + implementationType, + callSiteChain, + parameters, + throwIfCallSiteNotFound: false); + + if (currentParameterCallSites != null) + { + if (bestConstructor == null) + { + bestConstructor = constructors[i]; + parameterCallSites = currentParameterCallSites; + } + else + { + // Since we're visiting constructors in decreasing order of number of parameters, + // we'll only see ambiguities or supersets once we've seen a 'bestConstructor'. + + if (bestConstructorParameterTypes == null) + { + bestConstructorParameterTypes = new HashSet( + bestConstructor.GetParameters().Select(p => p.ParameterType)); + } + + if (!bestConstructorParameterTypes.IsSupersetOf(parameters.Select(p => p.ParameterType))) + { + // Ambiguous match exception + var message = string.Join( + Environment.NewLine, + Resources.FormatAmbiguousConstructorException(implementationType), + bestConstructor, + constructors[i]); + throw new InvalidOperationException(message); + } + } + } + } + + if (bestConstructor == null) + { + throw new InvalidOperationException( + Resources.FormatUnableToActivateTypeException(implementationType)); + } + else + { + Debug.Assert(parameterCallSites != null); + return parameterCallSites.Length == 0 ? + (IServiceCallSite)new CreateInstanceCallSite(serviceType, implementationType) : + new ConstructorCallSite(serviceType, bestConstructor, parameterCallSites); + } + } + + private IServiceCallSite[] CreateArgumentCallSites( + Type serviceType, + Type implementationType, + CallSiteChain callSiteChain, + ParameterInfo[] parameters, + bool throwIfCallSiteNotFound) + { + var parameterCallSites = new IServiceCallSite[parameters.Length]; + for (var index = 0; index < parameters.Length; index++) + { + var callSite = CreateCallSite(parameters[index].ParameterType, callSiteChain); + + if (callSite == null && ParameterDefaultValue.TryGetDefaultValue(parameters[index], out var defaultValue)) + { + callSite = new ConstantCallSite(serviceType, defaultValue); + } + + if (callSite == null) + { + if (throwIfCallSiteNotFound) + { + throw new InvalidOperationException(Resources.FormatCannotResolveService( + parameters[index].ParameterType, + implementationType)); + } + + return null; + } + + parameterCallSites[index] = callSite; + } + + return parameterCallSites; + } + + + public void Add(Type type, IServiceCallSite serviceCallSite) + { + _callSiteCache[type] = serviceCallSite; + } + + private struct ServiceDescriptorCacheItem + { + private ServiceDescriptor _item; + private List _items; + + public ServiceDescriptor Last + { + get + { + if (_items != null && _items.Count > 0) + { + return _items[_items.Count - 1]; + } + + Debug.Assert(_item != null); + return _item; + } + } + + public int Count + { + get + { + if (_item == null) + { + Debug.Assert(_items == null); + return 0; + } + + return 1 + (_items?.Count ?? 0); + } + } + + public ServiceDescriptor this[int index] + { + get + { + if (index >= Count) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + + if (index == 0) + { + return _item; + } + + return _items[index - 1]; + } + } + + public ServiceDescriptorCacheItem Add(ServiceDescriptor descriptor) + { + var newCacheItem = new ServiceDescriptorCacheItem(); + if (_item == null) + { + Debug.Assert(_items == null); + newCacheItem._item = descriptor; + } + else + { + newCacheItem._item = _item; + newCacheItem._items = _items ?? new List(); + newCacheItem._items.Add(descriptor); + } + return newCacheItem; + } + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteKind.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteKind.cs new file mode 100644 index 00000000000..2feb21e7f77 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteKind.cs @@ -0,0 +1,25 @@ +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal enum CallSiteKind + { + Factory, + + Constructor, + + Constant, + + IEnumerable, + + ServiceProvider, + + Scope, + + Transient, + + CreateInstance, + + ServiceScopeFactory, + + Singleton + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteRuntimeResolver.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteRuntimeResolver.cs new file mode 100644 index 00000000000..52b780c8a94 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteRuntimeResolver.cs @@ -0,0 +1,106 @@ +using System; +using System.Runtime.ExceptionServices; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class CallSiteRuntimeResolver : CallSiteVisitor + { + public object Resolve(IServiceCallSite callSite, ServiceProviderEngineScope scope) + { + return VisitCallSite(callSite, scope); + } + + protected override object VisitTransient(TransientCallSite transientCallSite, ServiceProviderEngineScope scope) + { + return scope.CaptureDisposable( + VisitCallSite(transientCallSite.ServiceCallSite, scope)); + } + + protected override object VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope) + { + object[] parameterValues = new object[constructorCallSite.ParameterCallSites.Length]; + for (var index = 0; index < parameterValues.Length; index++) + { + parameterValues[index] = VisitCallSite(constructorCallSite.ParameterCallSites[index], scope); + } + + try + { + return constructorCallSite.ConstructorInfo.Invoke(parameterValues); + } + catch (Exception ex) when (ex.InnerException != null) + { + ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); + // The above line will always throw, but the compiler requires we throw explicitly. + throw; + } + } + + protected override object VisitSingleton(SingletonCallSite singletonCallSite, ServiceProviderEngineScope scope) + { + return VisitScoped(singletonCallSite, scope.Engine.Root); + } + + protected override object VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope) + { + lock (scope.ResolvedServices) + { + if (!scope.ResolvedServices.TryGetValue(scopedCallSite.CacheKey, out var resolved)) + { + resolved = VisitCallSite(scopedCallSite.ServiceCallSite, scope); + scope.CaptureDisposable(resolved); + scope.ResolvedServices.Add(scopedCallSite.CacheKey, resolved); + } + return resolved; + } + } + + protected override object VisitConstant(ConstantCallSite constantCallSite, ServiceProviderEngineScope scope) + { + return constantCallSite.DefaultValue; + } + + protected override object VisitCreateInstance(CreateInstanceCallSite createInstanceCallSite, ServiceProviderEngineScope scope) + { + try + { + return Activator.CreateInstance(createInstanceCallSite.ImplementationType); + } + catch (Exception ex) when (ex.InnerException != null) + { + ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); + // The above line will always throw, but the compiler requires we throw explicitly. + throw; + } + } + + protected override object VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, ServiceProviderEngineScope scope) + { + return scope; + } + + protected override object VisitServiceScopeFactory(ServiceScopeFactoryCallSite serviceScopeFactoryCallSite, ServiceProviderEngineScope scope) + { + return scope.Engine; + } + + protected override object VisitIEnumerable(IEnumerableCallSite enumerableCallSite, ServiceProviderEngineScope scope) + { + var array = Array.CreateInstance( + enumerableCallSite.ItemType, + enumerableCallSite.ServiceCallSites.Length); + + for (var index = 0; index < enumerableCallSite.ServiceCallSites.Length; index++) + { + var value = VisitCallSite(enumerableCallSite.ServiceCallSites[index], scope); + array.SetValue(value, index); + } + return array; + } + + protected override object VisitFactory(FactoryCallSite factoryCallSite, ServiceProviderEngineScope scope) + { + return factoryCallSite.Factory(scope); + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteValidator.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteValidator.cs new file mode 100644 index 00000000000..ed06475f002 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteValidator.cs @@ -0,0 +1,119 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Concurrent; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class CallSiteValidator: CallSiteVisitor + { + // Keys are services being resolved via GetService, values - first scoped service in their call site tree + private readonly ConcurrentDictionary _scopedServices = new ConcurrentDictionary(); + + public void ValidateCallSite(IServiceCallSite callSite) + { + var scoped = VisitCallSite(callSite, default); + if (scoped != null) + { + _scopedServices[callSite.ServiceType] = scoped; + } + } + + public void ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope) + { + if (ReferenceEquals(scope, rootScope) + && _scopedServices.TryGetValue(serviceType, out var scopedService)) + { + if (serviceType == scopedService) + { + throw new InvalidOperationException( + Resources.FormatDirectScopedResolvedFromRootException(serviceType, + nameof(ServiceLifetime.Scoped).ToLowerInvariant())); + } + + throw new InvalidOperationException( + Resources.FormatScopedResolvedFromRootException( + serviceType, + scopedService, + nameof(ServiceLifetime.Scoped).ToLowerInvariant())); + } + } + + protected override Type VisitTransient(TransientCallSite transientCallSite, CallSiteValidatorState state) + { + return VisitCallSite(transientCallSite.ServiceCallSite, state); + } + + protected override Type VisitConstructor(ConstructorCallSite constructorCallSite, CallSiteValidatorState state) + { + Type result = null; + foreach (var parameterCallSite in constructorCallSite.ParameterCallSites) + { + var scoped = VisitCallSite(parameterCallSite, state); + if (result == null) + { + result = scoped; + } + } + return result; + } + + protected override Type VisitIEnumerable(IEnumerableCallSite enumerableCallSite, + CallSiteValidatorState state) + { + Type result = null; + foreach (var serviceCallSite in enumerableCallSite.ServiceCallSites) + { + var scoped = VisitCallSite(serviceCallSite, state); + if (result == null) + { + result = scoped; + } + } + return result; + } + + protected override Type VisitSingleton(SingletonCallSite singletonCallSite, CallSiteValidatorState state) + { + state.Singleton = singletonCallSite; + return VisitCallSite(singletonCallSite.ServiceCallSite, state); + } + + protected override Type VisitScoped(ScopedCallSite scopedCallSite, CallSiteValidatorState state) + { + // We are fine with having ServiceScopeService requested by singletons + if (scopedCallSite.ServiceCallSite is ServiceScopeFactoryCallSite) + { + return null; + } + if (state.Singleton != null) + { + throw new InvalidOperationException(Resources.FormatScopedInSingletonException( + scopedCallSite.ServiceType, + state.Singleton.ServiceType, + nameof(ServiceLifetime.Scoped).ToLowerInvariant(), + nameof(ServiceLifetime.Singleton).ToLowerInvariant() + )); + } + + VisitCallSite(scopedCallSite.ServiceCallSite, state); + return scopedCallSite.ServiceType; + } + + protected override Type VisitConstant(ConstantCallSite constantCallSite, CallSiteValidatorState state) => null; + + protected override Type VisitCreateInstance(CreateInstanceCallSite createInstanceCallSite, CallSiteValidatorState state) => null; + + protected override Type VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, CallSiteValidatorState state) => null; + + protected override Type VisitServiceScopeFactory(ServiceScopeFactoryCallSite serviceScopeFactoryCallSite, CallSiteValidatorState state) => null; + + protected override Type VisitFactory(FactoryCallSite factoryCallSite, CallSiteValidatorState state) => null; + + internal struct CallSiteValidatorState + { + public SingletonCallSite Singleton { get; set; } + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteVisitor.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteVisitor.cs new file mode 100644 index 00000000000..9d5a4c7ad5e --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteVisitor.cs @@ -0,0 +1,56 @@ +using System; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal abstract class CallSiteVisitor + { + protected virtual TResult VisitCallSite(IServiceCallSite callSite, TArgument argument) + { + switch (callSite.Kind) + { + case CallSiteKind.Factory: + return VisitFactory((FactoryCallSite)callSite, argument); + case CallSiteKind.IEnumerable: + return VisitIEnumerable((IEnumerableCallSite)callSite, argument); + case CallSiteKind.Constructor: + return VisitConstructor((ConstructorCallSite)callSite, argument); + case CallSiteKind.Transient: + return VisitTransient((TransientCallSite)callSite, argument); + case CallSiteKind.Singleton: + return VisitSingleton((SingletonCallSite)callSite, argument); + case CallSiteKind.Scope: + return VisitScoped((ScopedCallSite)callSite, argument); + case CallSiteKind.Constant: + return VisitConstant((ConstantCallSite)callSite, argument); + case CallSiteKind.CreateInstance: + return VisitCreateInstance((CreateInstanceCallSite)callSite, argument); + case CallSiteKind.ServiceProvider: + return VisitServiceProvider((ServiceProviderCallSite)callSite, argument); + case CallSiteKind.ServiceScopeFactory: + return VisitServiceScopeFactory((ServiceScopeFactoryCallSite)callSite, argument); + default: + throw new NotSupportedException($"Call site type {callSite.GetType()} is not supported"); + } + } + + protected abstract TResult VisitTransient(TransientCallSite transientCallSite, TArgument argument); + + protected abstract TResult VisitConstructor(ConstructorCallSite constructorCallSite, TArgument argument); + + protected abstract TResult VisitSingleton(SingletonCallSite singletonCallSite, TArgument argument); + + protected abstract TResult VisitScoped(ScopedCallSite scopedCallSite, TArgument argument); + + protected abstract TResult VisitConstant(ConstantCallSite constantCallSite, TArgument argument); + + protected abstract TResult VisitCreateInstance(CreateInstanceCallSite createInstanceCallSite, TArgument argument); + + protected abstract TResult VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, TArgument argument); + + protected abstract TResult VisitServiceScopeFactory(ServiceScopeFactoryCallSite serviceScopeFactoryCallSite, TArgument argument); + + protected abstract TResult VisitIEnumerable(IEnumerableCallSite enumerableCallSite, TArgument argument); + + protected abstract TResult VisitFactory(FactoryCallSite factoryCallSite, TArgument argument); + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CompiledServiceProviderEngine.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CompiledServiceProviderEngine.cs new file mode 100644 index 00000000000..76773ca4b0d --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CompiledServiceProviderEngine.cs @@ -0,0 +1,25 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal abstract class CompiledServiceProviderEngine : ServiceProviderEngine + { + public ExpressionResolverBuilder ExpressionResolverBuilder { get; } + + public CompiledServiceProviderEngine(IEnumerable serviceDescriptors, IServiceProviderEngineCallback callback) : base(serviceDescriptors, callback) + { + ExpressionResolverBuilder = new ExpressionResolverBuilder(RuntimeResolver, this, Root); + } + + protected override Func RealizeService(IServiceCallSite callSite) + { + var realizedService = ExpressionResolverBuilder.Build(callSite); + RealizedServices[callSite.ServiceType] = realizedService; + return realizedService; + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ConstantCallSite.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ConstantCallSite.cs new file mode 100644 index 00000000000..e547fc66f4b --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ConstantCallSite.cs @@ -0,0 +1,21 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class ConstantCallSite : IServiceCallSite + { + internal object DefaultValue { get; } + + public ConstantCallSite(Type serviceType, object defaultValue) + { + DefaultValue = defaultValue; + } + + public Type ServiceType => DefaultValue.GetType(); + public Type ImplementationType => DefaultValue.GetType(); + public CallSiteKind Kind { get; } = CallSiteKind.Constant; + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ConstructorCallSite.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ConstructorCallSite.cs new file mode 100644 index 00000000000..28e48065396 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ConstructorCallSite.cs @@ -0,0 +1,26 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Reflection; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class ConstructorCallSite : IServiceCallSite + { + internal ConstructorInfo ConstructorInfo { get; } + internal IServiceCallSite[] ParameterCallSites { get; } + + public ConstructorCallSite(Type serviceType, ConstructorInfo constructorInfo, IServiceCallSite[] parameterCallSites) + { + ServiceType = serviceType; + ConstructorInfo = constructorInfo; + ParameterCallSites = parameterCallSites; + } + + public Type ServiceType { get; } + + public Type ImplementationType => ConstructorInfo.DeclaringType; + public CallSiteKind Kind { get; } = CallSiteKind.Constructor; + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CreateInstanceCallSite.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CreateInstanceCallSite.cs new file mode 100644 index 00000000000..40072033576 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CreateInstanceCallSite.cs @@ -0,0 +1,22 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Runtime.ExceptionServices; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class CreateInstanceCallSite : IServiceCallSite + { + public Type ServiceType { get; } + + public Type ImplementationType { get; } + public CallSiteKind Kind { get; } = CallSiteKind.CreateInstance; + + public CreateInstanceCallSite(Type serviceType, Type implementationType) + { + ServiceType = serviceType; + ImplementationType = implementationType; + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/DynamicServiceProviderEngine.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/DynamicServiceProviderEngine.cs new file mode 100644 index 00000000000..08b933c9a4d --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/DynamicServiceProviderEngine.cs @@ -0,0 +1,30 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class DynamicServiceProviderEngine : CompiledServiceProviderEngine + { + public DynamicServiceProviderEngine(IEnumerable serviceDescriptors, IServiceProviderEngineCallback callback) : base(serviceDescriptors, callback) + { + } + + protected override Func RealizeService(IServiceCallSite callSite) + { + var callCount = 0; + return scope => + { + if (Interlocked.Increment(ref callCount) == 2) + { + Task.Run(() => base.RealizeService(callSite)); + } + return RuntimeResolver.Resolve(callSite, scope); + }; + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/Expressions/ExpressionResolverBuilder.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/Expressions/ExpressionResolverBuilder.cs new file mode 100644 index 00000000000..4478d9c9785 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/Expressions/ExpressionResolverBuilder.cs @@ -0,0 +1,295 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Threading; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class ExpressionResolverBuilder : CallSiteVisitor + { + internal static readonly MethodInfo InvokeFactoryMethodInfo = GetMethodInfo, IServiceProvider>>((a, b) => a.Invoke(b)); + internal static readonly MethodInfo CaptureDisposableMethodInfo = GetMethodInfo>((a, b) => a.CaptureDisposable(b)); + internal static readonly MethodInfo TryGetValueMethodInfo = GetMethodInfo, object, object, bool>>((a, b, c) => a.TryGetValue(b, out c)); + internal static readonly MethodInfo AddMethodInfo = GetMethodInfo, object, object>>((a, b, c) => a.Add(b, c)); + internal static readonly MethodInfo MonitorEnterMethodInfo = GetMethodInfo>((lockObj, lockTaken) => Monitor.Enter(lockObj, ref lockTaken)); + internal static readonly MethodInfo MonitorExitMethodInfo = GetMethodInfo>(lockObj => Monitor.Exit(lockObj)); + internal static readonly MethodInfo CallSiteRuntimeResolverResolve = + GetMethodInfo>((r, c, p) => r.Resolve(c, p)); + + internal static readonly MethodInfo ArrayEmptyMethodInfo = typeof(Array).GetMethod(nameof(Array.Empty)); + + private static readonly ParameterExpression ScopeParameter = Expression.Parameter(typeof(ServiceProviderEngineScope)); + + private static readonly ParameterExpression ResolvedServices = Expression.Variable(typeof(IDictionary), ScopeParameter.Name + "resolvedServices"); + private static readonly BinaryExpression ResolvedServicesVariableAssignment = + Expression.Assign(ResolvedServices, + Expression.Property(ScopeParameter, nameof(ServiceProviderEngineScope.ResolvedServices))); + + private static readonly ParameterExpression CaptureDisposableParameter = Expression.Parameter(typeof(object)); + private static readonly LambdaExpression CaptureDisposable = Expression.Lambda( + Expression.Call(ScopeParameter, CaptureDisposableMethodInfo, CaptureDisposableParameter), + CaptureDisposableParameter); + + private readonly CallSiteRuntimeResolver _runtimeResolver; + + private readonly IServiceScopeFactory _serviceScopeFactory; + + private readonly ServiceProviderEngineScope _rootScope; + + public ExpressionResolverBuilder(CallSiteRuntimeResolver runtimeResolver, IServiceScopeFactory serviceScopeFactory, ServiceProviderEngineScope rootScope) + { + if (runtimeResolver == null) + { + throw new ArgumentNullException(nameof(runtimeResolver)); + } + _runtimeResolver = runtimeResolver; + _serviceScopeFactory = serviceScopeFactory; + _rootScope = rootScope; + } + + public Func Build(IServiceCallSite callSite) + { + if (callSite is SingletonCallSite singletonCallSite) + { + // If root call site is singleton we can return Func calling + // _runtimeResolver.Resolve directly and avoid Expression generation + if (TryResolveSingletonValue(singletonCallSite, out var value)) + { + return scope => value; + } + + return scope => _runtimeResolver.Resolve(callSite, scope); + } + + return BuildExpression(callSite).Compile(); + } + + private bool TryResolveSingletonValue(SingletonCallSite singletonCallSite, out object value) + { + lock (_rootScope.ResolvedServices) + { + return _rootScope.ResolvedServices.TryGetValue(singletonCallSite.CacheKey, out value); + } + } + + private Expression> BuildExpression(IServiceCallSite callSite) + { + var context = new CallSiteExpressionBuilderContext + { + ScopeParameter = ScopeParameter + }; + + var serviceExpression = VisitCallSite(callSite, context); + + if (context.RequiresResolvedServices) + { + return Expression.Lambda>( + Expression.Block( + new [] { ResolvedServices }, + ResolvedServicesVariableAssignment, + Lock(serviceExpression, ResolvedServices)), + ScopeParameter); + } + + return Expression.Lambda>(serviceExpression, ScopeParameter); + } + + protected override Expression VisitSingleton(SingletonCallSite singletonCallSite, CallSiteExpressionBuilderContext context) + { + if (TryResolveSingletonValue(singletonCallSite, out var value)) + { + return Expression.Constant(value); + } + + return Expression.Call( + Expression.Constant(_runtimeResolver), + CallSiteRuntimeResolverResolve, + Expression.Constant(singletonCallSite, typeof(IServiceCallSite)), + context.ScopeParameter); + } + + protected override Expression VisitConstant(ConstantCallSite constantCallSite, CallSiteExpressionBuilderContext context) + { + return Expression.Constant(constantCallSite.DefaultValue); + } + + protected override Expression VisitCreateInstance(CreateInstanceCallSite createInstanceCallSite, CallSiteExpressionBuilderContext context) + { + return Expression.New(createInstanceCallSite.ImplementationType); + } + + protected override Expression VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, CallSiteExpressionBuilderContext context) + { + return context.ScopeParameter; + } + + protected override Expression VisitServiceScopeFactory(ServiceScopeFactoryCallSite serviceScopeFactoryCallSite, CallSiteExpressionBuilderContext context) + { + return Expression.Constant(_serviceScopeFactory); + } + + protected override Expression VisitFactory(FactoryCallSite factoryCallSite, CallSiteExpressionBuilderContext context) + { + return Expression.Invoke(Expression.Constant(factoryCallSite.Factory), context.ScopeParameter); + } + + protected override Expression VisitIEnumerable(IEnumerableCallSite callSite, CallSiteExpressionBuilderContext context) + { + if (callSite.ServiceCallSites.Length == 0) + { + return Expression.Constant(ArrayEmptyMethodInfo + .MakeGenericMethod(callSite.ItemType) + .Invoke(obj: null, parameters: Array.Empty())); + } + + return Expression.NewArrayInit( + callSite.ItemType, + callSite.ServiceCallSites.Select(cs => + Convert( + VisitCallSite(cs, context), + callSite.ItemType))); + } + + protected override Expression VisitTransient(TransientCallSite callSite, CallSiteExpressionBuilderContext context) + { + var implType = callSite.ServiceCallSite.ImplementationType; + // Elide calls to GetCaptureDisposable if the implemenation type isn't disposable + return TryCaptureDisposible( + implType, + context.ScopeParameter, + VisitCallSite(callSite.ServiceCallSite, context)); + } + + private Expression TryCaptureDisposible(Type implType, ParameterExpression scope, Expression service) + { + if (implType != null && + !typeof(IDisposable).GetTypeInfo().IsAssignableFrom(implType.GetTypeInfo())) + { + return service; + } + + return Expression.Invoke(GetCaptureDisposable(scope), + service); + } + + protected override Expression VisitConstructor(ConstructorCallSite callSite, CallSiteExpressionBuilderContext context) + { + var parameters = callSite.ConstructorInfo.GetParameters(); + var parameterExpressions = new Expression[callSite.ParameterCallSites.Length]; + for (int i = 0; i < parameterExpressions.Length; i++) + { + parameterExpressions[i] = Convert(VisitCallSite(callSite.ParameterCallSites[i], context), parameters[i].ParameterType); + } + return Expression.New(callSite.ConstructorInfo, parameterExpressions); + } + + private static Expression Convert(Expression expression, Type type) + { + // Don't convert if the expression is already assignable + if (type.GetTypeInfo().IsAssignableFrom(expression.Type.GetTypeInfo())) + { + return expression; + } + + return Expression.Convert(expression, type); + } + + protected override Expression VisitScoped(ScopedCallSite callSite, CallSiteExpressionBuilderContext context) + { + return BuildScopedExpression(callSite, context, VisitCallSite(callSite.ServiceCallSite, context)); + } + + // Move off the main stack + private Expression BuildScopedExpression(ScopedCallSite callSite, CallSiteExpressionBuilderContext context, Expression service) + { + var keyExpression = Expression.Constant( + callSite.CacheKey, + typeof(object)); + + var resolvedVariable = Expression.Variable(typeof(object), "resolved"); + + var resolvedServices = GetResolvedServices(context); + + var tryGetValueExpression = Expression.Call( + resolvedServices, + TryGetValueMethodInfo, + keyExpression, + resolvedVariable); + + var captureDisposible = TryCaptureDisposible(callSite.ImplementationType, context.ScopeParameter, service); + + var assignExpression = Expression.Assign( + resolvedVariable, + captureDisposible); + + var addValueExpression = Expression.Call( + resolvedServices, + AddMethodInfo, + keyExpression, + resolvedVariable); + + var blockExpression = Expression.Block( + typeof(object), + new[] + { + resolvedVariable + }, + Expression.IfThen( + Expression.Not(tryGetValueExpression), + Expression.Block( + assignExpression, + addValueExpression)), + resolvedVariable); + + return blockExpression; + } + + private static MethodInfo GetMethodInfo(Expression expr) + { + var mc = (MethodCallExpression)expr.Body; + return mc.Method; + } + + public Expression GetCaptureDisposable(ParameterExpression scope) + { + if (scope != ScopeParameter) + { + throw new NotSupportedException("GetCaptureDisposable call is supported only for main scope"); + } + return CaptureDisposable; + } + + public Expression GetResolvedServices(CallSiteExpressionBuilderContext context) + { + if (context.ScopeParameter != ScopeParameter) + { + throw new NotSupportedException("GetResolvedServices call is supported only for main scope"); + } + context.RequiresResolvedServices = true; + return ResolvedServices; + } + + private static Expression Lock(Expression body, Expression syncVariable) + { + // The C# compiler would copy the lock object to guard against mutation. + // We don't, since we know the lock object is readonly. + var lockWasTaken = Expression.Variable(typeof(bool), "lockWasTaken"); + + var monitorEnter = Expression.Call(MonitorEnterMethodInfo, syncVariable, lockWasTaken); + var monitorExit = Expression.Call(MonitorExitMethodInfo, syncVariable); + + var tryBody = Expression.Block(monitorEnter, body); + var finallyBody = Expression.IfThen(lockWasTaken, monitorExit); + + return Expression.Block( + typeof(object), + new[] { lockWasTaken }, + Expression.TryFinally(tryBody, finallyBody)); + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/Expressions/ExpressionsServiceProviderEngine.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/Expressions/ExpressionsServiceProviderEngine.cs new file mode 100644 index 00000000000..f7b55a44498 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/Expressions/ExpressionsServiceProviderEngine.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class ExpressionsServiceProviderEngine : ServiceProviderEngine + { + private readonly ExpressionResolverBuilder _expressionResolverBuilder; + public ExpressionsServiceProviderEngine(IEnumerable serviceDescriptors, IServiceProviderEngineCallback callback) : base(serviceDescriptors, callback) + { + _expressionResolverBuilder = new ExpressionResolverBuilder(RuntimeResolver, this, Root); + } + + protected override Func RealizeService(IServiceCallSite callSite) + { + var realizedService = _expressionResolverBuilder.Build(callSite); + RealizedServices[callSite.ServiceType] = realizedService; + return realizedService; + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/FactoryCallSite.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/FactoryCallSite.cs new file mode 100644 index 00000000000..548607d7c1d --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/FactoryCallSite.cs @@ -0,0 +1,23 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class FactoryCallSite : IServiceCallSite + { + public Func Factory { get; } + + public FactoryCallSite(Type serviceType, Func factory) + { + Factory = factory; + ServiceType = serviceType; + } + + public Type ServiceType { get; } + public Type ImplementationType => null; + + public CallSiteKind Kind { get; } = CallSiteKind.Factory; + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/IEnumerableCallSite.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/IEnumerableCallSite.cs new file mode 100644 index 00000000000..bbfb081d59c --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/IEnumerableCallSite.cs @@ -0,0 +1,24 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class IEnumerableCallSite : IServiceCallSite + { + internal Type ItemType { get; } + internal IServiceCallSite[] ServiceCallSites { get; } + + public IEnumerableCallSite(Type itemType, IServiceCallSite[] serviceCallSites) + { + ItemType = itemType; + ServiceCallSites = serviceCallSites; + } + + public Type ServiceType => typeof(IEnumerable<>).MakeGenericType(ItemType); + public Type ImplementationType => ItemType.MakeArrayType(); + public CallSiteKind Kind { get; } = CallSiteKind.IEnumerable; + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitCallSiteAnalysisResult.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitCallSiteAnalysisResult.cs new file mode 100644 index 00000000000..c1e28a81b2a --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitCallSiteAnalysisResult.cs @@ -0,0 +1,26 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal readonly struct ILEmitCallSiteAnalysisResult + { + public ILEmitCallSiteAnalysisResult(int size) : this() + { + Size = size; + } + + public ILEmitCallSiteAnalysisResult(int size, bool hasScope) + { + Size = size; + HasScope = hasScope; + } + + public readonly int Size; + + public readonly bool HasScope; + + public ILEmitCallSiteAnalysisResult Add(in ILEmitCallSiteAnalysisResult other) => + new ILEmitCallSiteAnalysisResult(Size + other.Size, HasScope | other.HasScope); + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitCallSiteAnalyzer.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitCallSiteAnalyzer.cs new file mode 100644 index 00000000000..25d4899d25e --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitCallSiteAnalyzer.cs @@ -0,0 +1,64 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + // This class walks the service call site tree and tries to calculate approximate + // code size to avoid array resizings during IL generation + // It also detects if lock is required for scoped services resolution + internal sealed class ILEmitCallSiteAnalyzer : CallSiteVisitor + { + private const int ConstructorILSize = 6; + + private const int ScopedILSize = 64; + + private const int ConstantILSize = 4; + + private const int ServiceProviderSize = 1; + + private const int FactoryILSize = 16; + + internal static ILEmitCallSiteAnalyzer Instance { get; } = new ILEmitCallSiteAnalyzer(); + + protected override ILEmitCallSiteAnalysisResult VisitTransient(TransientCallSite transientCallSite, object argument) => VisitCallSite(transientCallSite.ServiceCallSite, argument); + + protected override ILEmitCallSiteAnalysisResult VisitConstructor(ConstructorCallSite constructorCallSite, object argument) + { + var result = new ILEmitCallSiteAnalysisResult(ConstructorILSize); + foreach (var callSite in constructorCallSite.ParameterCallSites) + { + result = result.Add(VisitCallSite(callSite, argument)); + } + return result; + } + + protected override ILEmitCallSiteAnalysisResult VisitSingleton(SingletonCallSite singletonCallSite, object argument) => VisitCallSite(singletonCallSite.ServiceCallSite, argument); + + protected override ILEmitCallSiteAnalysisResult VisitScoped(ScopedCallSite scopedCallSite, object argument) + { + return new ILEmitCallSiteAnalysisResult(ScopedILSize, hasScope: true).Add(VisitCallSite(scopedCallSite.ServiceCallSite, argument)); + } + + protected override ILEmitCallSiteAnalysisResult VisitConstant(ConstantCallSite constantCallSite, object argument) => new ILEmitCallSiteAnalysisResult(ConstantILSize); + + protected override ILEmitCallSiteAnalysisResult VisitCreateInstance(CreateInstanceCallSite createInstanceCallSite, object argument) => new ILEmitCallSiteAnalysisResult(ConstructorILSize); + + protected override ILEmitCallSiteAnalysisResult VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, object argument) => new ILEmitCallSiteAnalysisResult(ServiceProviderSize); + + protected override ILEmitCallSiteAnalysisResult VisitServiceScopeFactory(ServiceScopeFactoryCallSite serviceScopeFactoryCallSite, object argument) => new ILEmitCallSiteAnalysisResult(ConstantILSize); + + protected override ILEmitCallSiteAnalysisResult VisitIEnumerable(IEnumerableCallSite enumerableCallSite, object argument) + { + var result = new ILEmitCallSiteAnalysisResult(ConstructorILSize); + foreach (var callSite in enumerableCallSite.ServiceCallSites) + { + result = result.Add(VisitCallSite(callSite, argument)); + } + return result; + } + + protected override ILEmitCallSiteAnalysisResult VisitFactory(FactoryCallSite factoryCallSite, object argument) => new ILEmitCallSiteAnalysisResult(FactoryILSize); + + public ILEmitCallSiteAnalysisResult CollectGenerationInfo(IServiceCallSite callSite) => VisitCallSite(callSite, null); + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilder.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilder.cs new file mode 100644 index 00000000000..b826f5d61b0 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilder.cs @@ -0,0 +1,460 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq.Expressions; +using System.Reflection; +using System.Reflection.Emit; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal sealed class ILEmitResolverBuilder : CallSiteVisitor + { + private static readonly MethodInfo ResolvedServicesGetter = typeof(ServiceProviderEngineScope).GetProperty( + nameof(ServiceProviderEngineScope.ResolvedServices), BindingFlags.Instance | BindingFlags.NonPublic).GetMethod; + + private static readonly FieldInfo RuntimeResolverField = typeof(ILEmitResolverBuilderRuntimeContext).GetField(nameof(ILEmitResolverBuilderRuntimeContext.RuntimeResolver)); + private static readonly FieldInfo RootField = typeof(ILEmitResolverBuilderRuntimeContext).GetField(nameof(ILEmitResolverBuilderRuntimeContext.Root)); + private static readonly FieldInfo FactoriesField = typeof(ILEmitResolverBuilderRuntimeContext).GetField(nameof(ILEmitResolverBuilderRuntimeContext.Factories)); + private static readonly FieldInfo ConstantsField = typeof(ILEmitResolverBuilderRuntimeContext).GetField(nameof(ILEmitResolverBuilderRuntimeContext.Constants)); + + private class ILEmitResolverBuilderRuntimeContext + { + public CallSiteRuntimeResolver RuntimeResolver; + public IServiceScopeFactory ScopeFactory; + public ServiceProviderEngineScope Root; + public object[] Constants; + public Func[] Factories; + } + + private readonly CallSiteRuntimeResolver _runtimeResolver; + + private readonly IServiceScopeFactory _serviceScopeFactory; + + private readonly ServiceProviderEngineScope _rootScope; + + public ILEmitResolverBuilder(CallSiteRuntimeResolver runtimeResolver, IServiceScopeFactory serviceScopeFactory, ServiceProviderEngineScope rootScope) + { + if (runtimeResolver == null) + { + throw new ArgumentNullException(nameof(runtimeResolver)); + } + _runtimeResolver = runtimeResolver; + _serviceScopeFactory = serviceScopeFactory; + _rootScope = rootScope; + } + + public Func Build(IServiceCallSite callSite) + { + if (callSite is SingletonCallSite singletonCallSite) + { + // If root call site is singleton we can return Func calling + // _runtimeResolver.Resolve directly and avoid Expression generation + if (TryResolveSingletonValue(singletonCallSite, out var value)) + { + return scope => value; + } + + return scope => _runtimeResolver.Resolve(callSite, scope); + } + + return BuildType(callSite); + } + + protected override Expression VisitTransient(TransientCallSite transientCallSite, ILEmitResolverBuilderContext argument) + { + // RuntimeScope.CaptureDisposables([create value]) + var shouldCapture = BeginCaptureDisposable(transientCallSite.ServiceCallSite.ImplementationType, argument); + + VisitCallSite(transientCallSite.ServiceCallSite, argument); + + if (shouldCapture) + { + EndCaptureDisposable(argument); + } + return null; + } + + protected override Expression VisitConstructor(ConstructorCallSite constructorCallSite, ILEmitResolverBuilderContext argument) + { + // new T([create arguments]) + foreach (var parameterCallSite in constructorCallSite.ParameterCallSites) + { + VisitCallSite(parameterCallSite, argument); + } + argument.Generator.Emit(OpCodes.Newobj, constructorCallSite.ConstructorInfo); + return null; + } + + protected override Expression VisitSingleton(SingletonCallSite singletonCallSite, ILEmitResolverBuilderContext argument) + { + if (TryResolveSingletonValue(singletonCallSite, out var value)) + { + AddConstant(argument, value); + return null; + } + + // this.RuntimeResolver.Resolve(singletonCallSite) + + argument.Generator.Emit(OpCodes.Ldarg_0); + argument.Generator.Emit(OpCodes.Ldfld, RuntimeResolverField); + + AddConstant(argument, singletonCallSite); + + argument.Generator.Emit(OpCodes.Ldarg_0); + argument.Generator.Emit(OpCodes.Ldfld, RootField); + + argument.Generator.Emit(OpCodes.Callvirt, ExpressionResolverBuilder.CallSiteRuntimeResolverResolve); + return null; + } + + protected override Expression VisitScoped(ScopedCallSite scopedCallSite, ILEmitResolverBuilderContext argument) + { + + // var cacheKey = scopedCallSite.CacheKey; + // if (ProviderScope.ResolvedServices.TryGetValue(cacheKey, out value) + // { + // [return] value + // } + // else + // { + // value = [createvalue]; + // ProviderScope.ResolvedServices.Add(cacheKey, value); + // } + + var resultLocal = argument.Generator.DeclareLocal(scopedCallSite.ServiceType); + var cacheKeyLocal = argument.Generator.DeclareLocal(typeof(object)); + var endLabel = argument.Generator.DefineLabel(); + + // Resolved services would be 0 local + argument.Generator.Emit(OpCodes.Ldloc_0); + + AddConstant(argument, scopedCallSite.CacheKey); + // Duplicate cache key + argument.Generator.Emit(OpCodes.Dup); + // and store to local + Stloc(argument.Generator, cacheKeyLocal.LocalIndex); + + // Load address of local + argument.Generator.Emit(OpCodes.Ldloca, resultLocal.LocalIndex); + // .TryGetValue + argument.Generator.Emit(OpCodes.Callvirt, ExpressionResolverBuilder.TryGetValueMethodInfo); + + // Jump to create new if nothing in cache + argument.Generator.Emit(OpCodes.Brtrue, endLabel); + + var shouldCapture = BeginCaptureDisposable(scopedCallSite.ServiceCallSite.ImplementationType, argument); + + VisitCallSite(scopedCallSite.ServiceCallSite, argument); + + if (shouldCapture) + { + EndCaptureDisposable(argument); + } + + // Store return value into var + argument.Generator.Emit(OpCodes.Stloc, resultLocal.LocalIndex); + + argument.Generator.Emit(OpCodes.Ldloc_0); + // Load cache key + Ldloc(argument.Generator, cacheKeyLocal.LocalIndex); + // Load value + Ldloc(argument.Generator, resultLocal.LocalIndex); + + argument.Generator.Emit(OpCodes.Callvirt, ExpressionResolverBuilder.AddMethodInfo); + + // Load result and return it + argument.Generator.MarkLabel(endLabel); + Ldloc(argument.Generator, resultLocal.LocalIndex); + + return null; + } + + protected override Expression VisitConstant(ConstantCallSite constantCallSite, ILEmitResolverBuilderContext argument) + { + AddConstant(argument, constantCallSite.DefaultValue); + return null; + } + + protected override Expression VisitCreateInstance(CreateInstanceCallSite createInstanceCallSite, ILEmitResolverBuilderContext argument) + { + // new Type + argument.Generator.Emit(OpCodes.Newobj, createInstanceCallSite.ImplementationType.GetConstructor(Type.EmptyTypes)); + return null; + } + + protected override Expression VisitServiceProvider(ServiceProviderCallSite serviceProviderCallSite, ILEmitResolverBuilderContext argument) + { + // [return] ProviderScope + argument.Generator.Emit(OpCodes.Ldarg_1); + return null; + } + + protected override Expression VisitServiceScopeFactory(ServiceScopeFactoryCallSite serviceScopeFactoryCallSite, ILEmitResolverBuilderContext argument) + { + // this.ScopeFactory + argument.Generator.Emit(OpCodes.Ldarg_0); + argument.Generator.Emit(OpCodes.Ldfld, typeof(ILEmitResolverBuilderRuntimeContext).GetField(nameof(ILEmitResolverBuilderRuntimeContext.ScopeFactory))); + return null; + } + + protected override Expression VisitIEnumerable(IEnumerableCallSite enumerableCallSite, ILEmitResolverBuilderContext argument) + { + + if (enumerableCallSite.ServiceCallSites.Length == 0) + { + argument.Generator.Emit(OpCodes.Call, ExpressionResolverBuilder.ArrayEmptyMethodInfo.MakeGenericMethod(enumerableCallSite.ItemType)); + } + else + { + + // var array = new ItemType[]; + // array[0] = [Create argument0]; + // array[1] = [Create argument1]; + // ... + argument.Generator.Emit(OpCodes.Ldc_I4, enumerableCallSite.ServiceCallSites.Length); + argument.Generator.Emit(OpCodes.Newarr, enumerableCallSite.ItemType); + for (int i = 0; i < enumerableCallSite.ServiceCallSites.Length; i++) + { + // duplicate array + argument.Generator.Emit(OpCodes.Dup); + // push index + argument.Generator.Emit(OpCodes.Ldc_I4, i); + // create parameter + VisitCallSite(enumerableCallSite.ServiceCallSites[i], argument); + // store + argument.Generator.Emit(OpCodes.Stelem, enumerableCallSite.ItemType); + } + } + + return null; + } + + protected override Expression VisitFactory(FactoryCallSite factoryCallSite, ILEmitResolverBuilderContext argument) + { + if (argument.Factories == null) + { + argument.Factories = new List>(); + } + + // this.Factories[i](ProviderScope) + argument.Generator.Emit(OpCodes.Ldarg_0); + argument.Generator.Emit(OpCodes.Ldfld, FactoriesField); + + argument.Generator.Emit(OpCodes.Ldc_I4, argument.Factories.Count); + argument.Generator.Emit(OpCodes.Ldelem, typeof(Func)); + + argument.Generator.Emit(OpCodes.Ldarg_1); + argument.Generator.Emit(OpCodes.Call, ExpressionResolverBuilder.InvokeFactoryMethodInfo); + + argument.Factories.Add(factoryCallSite.Factory); + return null; + } + + private void AddConstant(ILEmitResolverBuilderContext argument, object value) + { + if (argument.Constants == null) + { + argument.Constants = new List(); + } + + // this.Constants[i] + argument.Generator.Emit(OpCodes.Ldarg_0); + argument.Generator.Emit(OpCodes.Ldfld, ConstantsField); + + argument.Generator.Emit(OpCodes.Ldc_I4, argument.Constants.Count); + argument.Generator.Emit(OpCodes.Ldelem, typeof(object)); + argument.Constants.Add(value); + } + + + private Func BuildType(IServiceCallSite callSite) + { + // We need to skip visibility checks because services/constructors might be private + var dynamicMethod = new DynamicMethod("ResolveService", + attributes: MethodAttributes.Public | MethodAttributes.Static, + callingConvention: CallingConventions.Standard, + returnType: typeof(object), + parameterTypes: new [] {typeof(ILEmitResolverBuilderRuntimeContext), typeof(ServiceProviderEngineScope) }, + owner: GetType(), + skipVisibility: true); + + var info = ILEmitCallSiteAnalyzer.Instance.CollectGenerationInfo(callSite); + var runtimeContext = GenerateMethodBody(callSite, dynamicMethod.GetILGenerator(info.Size), info); + +#if SAVE_ASSEMBLY + var assemblyName = "Test" + DateTime.Now.Ticks; + + var fileName = "Test" + DateTime.Now.Ticks; + var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.RunAndSave); + var module = assembly.DefineDynamicModule(assemblyName, assemblyName+".dll"); + var type = module.DefineType("Resolver"); + + var method = type.DefineMethod( + "ResolveService", MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, typeof(object), + new[] { typeof(ILEmitResolverBuilderRuntimeContext), typeof(ServiceProviderEngineScope) }); + + GenerateMethodBody(callSite, method.GetILGenerator(), info); + type.CreateTypeInfo(); + assembly.Save(assemblyName+".dll"); +#endif + + return (Func)dynamicMethod.CreateDelegate(typeof(Func), runtimeContext); + } + + private ILEmitResolverBuilderRuntimeContext GenerateMethodBody(IServiceCallSite callSite, ILGenerator generator, ILEmitCallSiteAnalysisResult info) + { + var context = new ILEmitResolverBuilderContext() + { + Generator = generator, + Constants = null, + Factories = null + }; + + // try + // { + // Monitor.Enter(scope.ResolvedServices, out var lockTaken); + // return [ create value ] + // } + // finally + // { + // if (lockTaken) Monitor.Exit(scope.ResolvedServices); + // } + + + var hasScopes = info.HasScope; + if (hasScopes) + { + // Has to be first local defined + var resolvedServicesLocal = context.Generator.DeclareLocal(typeof(IDictionary)); + Debug.Assert(resolvedServicesLocal.LocalIndex == 0); + var lockTakenLocal = context.Generator.DeclareLocal(typeof(bool)); + Debug.Assert(lockTakenLocal.LocalIndex == 1); + + context.Generator.BeginExceptionBlock(); + + // scope + context.Generator.Emit(OpCodes.Ldarg_1); + // .ResolvedServices + context.Generator.Emit(OpCodes.Callvirt, ResolvedServicesGetter); + + context.Generator.Emit(OpCodes.Dup); + // Store resolved services + context.Generator.Emit(OpCodes.Stloc_0); + context.Generator.Emit(OpCodes.Ldloca_S, 1); + + // Monitor.Enter + context.Generator.Emit(OpCodes.Call, ExpressionResolverBuilder.MonitorEnterMethodInfo); + } + + VisitCallSite(callSite, context); + + if (hasScopes) + { + var resultLocal = context.Generator.DeclareLocal(typeof(object)); + + Stloc(context.Generator, resultLocal.LocalIndex); + context.Generator.BeginFinallyBlock(); + + var postExitLabel = context.Generator.DefineLabel(); + context.Generator.Emit(OpCodes.Ldloc_1); + context.Generator.Emit(OpCodes.Brfalse, postExitLabel); + + context.Generator.Emit(OpCodes.Ldloc, 0); + + // Monitor.Exit + context.Generator.Emit(OpCodes.Call, ExpressionResolverBuilder.MonitorExitMethodInfo); + context.Generator.MarkLabel(postExitLabel); + + context.Generator.EndExceptionBlock(); + + Ldloc(context.Generator, resultLocal.LocalIndex); + } + + context.Generator.Emit(OpCodes.Ret); + return new ILEmitResolverBuilderRuntimeContext + { + Constants = context.Constants?.ToArray(), + Factories = context.Factories?.ToArray(), + Root = _rootScope, + RuntimeResolver = _runtimeResolver, + ScopeFactory = _serviceScopeFactory + }; + } + + private bool TryResolveSingletonValue(SingletonCallSite singletonCallSite, out object value) + { + lock (_rootScope.ResolvedServices) + { + return _rootScope.ResolvedServices.TryGetValue(singletonCallSite.CacheKey, out value); + } + } + + private static bool BeginCaptureDisposable(Type implType, ILEmitResolverBuilderContext argument) + { + var shouldCapture = implType == null || typeof(IDisposable).GetTypeInfo().IsAssignableFrom(implType.GetTypeInfo()); + + if (shouldCapture) + { + // context + argument.Generator.Emit(OpCodes.Ldarg_1); + } + + return shouldCapture; + } + + private static void EndCaptureDisposable(ILEmitResolverBuilderContext argument) + { + // Call CaptureDisposabl we expect calee and arguments to be on the stackcontext.Generator.BeginExceptionBlock + argument.Generator.Emit(OpCodes.Callvirt, ExpressionResolverBuilder.CaptureDisposableMethodInfo); + } + + private void Ldloc(ILGenerator generator, int index) + { + switch (index) + { + case 0: generator.Emit(OpCodes.Ldloc_0); + return; + case 1: generator.Emit(OpCodes.Ldloc_1); + return; + case 2: generator.Emit(OpCodes.Ldloc_2); + return; + case 3: generator.Emit(OpCodes.Ldloc_3); + return; + } + + if (index < byte.MaxValue) + { + generator.Emit(OpCodes.Ldloc_S, (byte)index); + return; + } + + generator.Emit(OpCodes.Ldloc, index); + } + + private void Stloc(ILGenerator generator, int index) + { + switch (index) + { + case 0: generator.Emit(OpCodes.Stloc_0); + return; + case 1: generator.Emit(OpCodes.Stloc_1); + return; + case 2: generator.Emit(OpCodes.Stloc_2); + return; + case 3: generator.Emit(OpCodes.Stloc_3); + return; + } + + if (index < byte.MaxValue) + { + generator.Emit(OpCodes.Stloc_S, (byte)index); + return; + } + + generator.Emit(OpCodes.Stloc, index); + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilderContext.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilderContext.cs new file mode 100644 index 00000000000..2d74b93a85b --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilderContext.cs @@ -0,0 +1,16 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Reflection.Emit; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class ILEmitResolverBuilderContext + { + public ILGenerator Generator { get; set; } + public List Constants { get; set; } + public List> Factories { get; set; } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitServiceProviderEngine.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitServiceProviderEngine.cs new file mode 100644 index 00000000000..e0a888b65ca --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitServiceProviderEngine.cs @@ -0,0 +1,24 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class ILEmitServiceProviderEngine : ServiceProviderEngine + { + private readonly ILEmitResolverBuilder _expressionResolverBuilder; + public ILEmitServiceProviderEngine(IEnumerable serviceDescriptors, IServiceProviderEngineCallback callback) : base(serviceDescriptors, callback) + { + _expressionResolverBuilder = new ILEmitResolverBuilder(RuntimeResolver, this, Root); + } + + protected override Func RealizeService(IServiceCallSite callSite) + { + var realizedService = _expressionResolverBuilder.Build(callSite); + RealizedServices[callSite.ServiceType] = realizedService; + return realizedService; + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/IServiceCallSite.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/IServiceCallSite.cs new file mode 100644 index 00000000000..e72e41548c8 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/IServiceCallSite.cs @@ -0,0 +1,17 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + /// + /// Summary description for IServiceCallSite + /// + internal interface IServiceCallSite + { + Type ServiceType { get; } + Type ImplementationType { get; } + CallSiteKind Kind { get; } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/IServiceProviderEngine.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/IServiceProviderEngine.cs new file mode 100644 index 00000000000..08204f2eeb5 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/IServiceProviderEngine.cs @@ -0,0 +1,12 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal interface IServiceProviderEngine : IDisposable, IServiceProvider + { + IServiceScope RootScope { get; } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/IServiceProviderEngineCallback.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/IServiceProviderEngineCallback.cs new file mode 100644 index 00000000000..f30f1ff17be --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/IServiceProviderEngineCallback.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal interface IServiceProviderEngineCallback + { + void OnCreate(IServiceCallSite callSite); + void OnResolve(Type serviceType, IServiceScope scope); + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/RuntimeServiceProviderEngine.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/RuntimeServiceProviderEngine.cs new file mode 100644 index 00000000000..d6b7c9d312a --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/RuntimeServiceProviderEngine.cs @@ -0,0 +1,26 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class RuntimeServiceProviderEngine : ServiceProviderEngine + { + public RuntimeServiceProviderEngine(IEnumerable serviceDescriptors, IServiceProviderEngineCallback callback) : base(serviceDescriptors, callback) + { + } + + protected override Func RealizeService(IServiceCallSite callSite) + { + return scope => + { + Func realizedService = p => RuntimeResolver.Resolve(callSite, p); + + RealizedServices[callSite.ServiceType] = realizedService; + return realizedService(scope); + }; + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ScopedCallSite.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ScopedCallSite.cs new file mode 100644 index 00000000000..ef92d63150b --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ScopedCallSite.cs @@ -0,0 +1,23 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class ScopedCallSite : IServiceCallSite + { + internal IServiceCallSite ServiceCallSite { get; } + public object CacheKey { get; } + + public ScopedCallSite(IServiceCallSite serviceCallSite, object cacheKey) + { + ServiceCallSite = serviceCallSite; + CacheKey = cacheKey; + } + + public Type ServiceType => ServiceCallSite.ServiceType; + public Type ImplementationType => ServiceCallSite.ImplementationType; + public virtual CallSiteKind Kind { get; } = CallSiteKind.Scope; + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ServiceProviderCallSite.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ServiceProviderCallSite.cs new file mode 100644 index 00000000000..50628773bd9 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ServiceProviderCallSite.cs @@ -0,0 +1,14 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class ServiceProviderCallSite : IServiceCallSite + { + public Type ServiceType { get; } = typeof(IServiceProvider); + public Type ImplementationType { get; } = typeof(ServiceProvider); + public CallSiteKind Kind { get; } = CallSiteKind.ServiceProvider; + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ServiceProviderEngine.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ServiceProviderEngine.cs new file mode 100644 index 00000000000..d42c0b1f409 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ServiceProviderEngine.cs @@ -0,0 +1,84 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal abstract class ServiceProviderEngine : IServiceProviderEngine, IServiceScopeFactory + { + private readonly IServiceProviderEngineCallback _callback; + + private readonly Func> _createServiceAccessor; + + private bool _disposed; + + protected ServiceProviderEngine(IEnumerable serviceDescriptors, IServiceProviderEngineCallback callback) + { + _createServiceAccessor = CreateServiceAccessor; + _callback = callback; + Root = new ServiceProviderEngineScope(this); + RuntimeResolver = new CallSiteRuntimeResolver(); + CallSiteFactory = new CallSiteFactory(serviceDescriptors); + CallSiteFactory.Add(typeof(IServiceProvider), new ServiceProviderCallSite()); + CallSiteFactory.Add(typeof(IServiceScopeFactory), new ServiceScopeFactoryCallSite()); + RealizedServices = new ConcurrentDictionary>(); + } + + internal ConcurrentDictionary> RealizedServices { get; } + + internal CallSiteFactory CallSiteFactory { get; } + + protected CallSiteRuntimeResolver RuntimeResolver { get; } + + public ServiceProviderEngineScope Root { get; } + + public IServiceScope RootScope => Root; + + public object GetService(Type serviceType) => GetService(serviceType, Root); + + protected abstract Func RealizeService(IServiceCallSite callSite); + + public void Dispose() + { + _disposed = true; + Root.Dispose(); + } + + internal object GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope) + { + if (_disposed) + { + ThrowHelper.ThrowObjectDisposedException(); + } + + var realizedService = RealizedServices.GetOrAdd(serviceType, _createServiceAccessor); + _callback?.OnResolve(serviceType, serviceProviderEngineScope); + return realizedService.Invoke(serviceProviderEngineScope); + } + + public IServiceScope CreateScope() + { + if (_disposed) + { + ThrowHelper.ThrowObjectDisposedException(); + } + + return new ServiceProviderEngineScope(this); + } + + private Func CreateServiceAccessor(Type serviceType) + { + var callSite = CallSiteFactory.CreateCallSite(serviceType, new CallSiteChain()); + if (callSite != null) + { + _callback?.OnCreate(callSite); + return RealizeService(callSite); + } + + return _ => null; + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ServiceProviderEngineScope.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ServiceProviderEngineScope.cs new file mode 100644 index 00000000000..5b876cd24e2 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ServiceProviderEngineScope.cs @@ -0,0 +1,86 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class ServiceProviderEngineScope : IServiceScope, IServiceProvider + { + // For testing only + internal Action _captureDisposableCallback; + + private List _disposables; + + private bool _disposed; + + public ServiceProviderEngineScope(ServiceProviderEngine engine) + { + Engine = engine; + } + + internal Dictionary ResolvedServices { get; } = new Dictionary(); + + public ServiceProviderEngine Engine { get; } + + public object GetService(Type serviceType) + { + if (_disposed) + { + ThrowHelper.ThrowObjectDisposedException(); + } + + return Engine.GetService(serviceType, this); + } + + public IServiceProvider ServiceProvider => this; + + public void Dispose() + { + lock (ResolvedServices) + { + if (_disposed) + { + return; + } + + _disposed = true; + if (_disposables != null) + { + for (var i = _disposables.Count - 1; i >= 0; i--) + { + var disposable = _disposables[i]; + disposable.Dispose(); + } + + _disposables.Clear(); + } + + ResolvedServices.Clear(); + } + } + + internal object CaptureDisposable(object service) + { + _captureDisposableCallback?.Invoke(service); + + if (!ReferenceEquals(this, service)) + { + if (service is IDisposable disposable) + { + lock (ResolvedServices) + { + if (_disposables == null) + { + _disposables = new List(); + } + + _disposables.Add(disposable); + } + } + } + return service; + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ServiceScopeFactoryCallSite.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ServiceScopeFactoryCallSite.cs new file mode 100644 index 00000000000..381440a6534 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ServiceScopeFactoryCallSite.cs @@ -0,0 +1,14 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class ServiceScopeFactoryCallSite : IServiceCallSite + { + public Type ServiceType { get; } = typeof(IServiceScopeFactory); + public Type ImplementationType { get; } = typeof(ServiceProviderEngine); + public CallSiteKind Kind { get; } = CallSiteKind.ServiceScopeFactory; + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/SingletonCallSite.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/SingletonCallSite.cs new file mode 100644 index 00000000000..dc902d8adda --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/SingletonCallSite.cs @@ -0,0 +1,14 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class SingletonCallSite : ScopedCallSite + { + public SingletonCallSite(IServiceCallSite serviceCallSite, object cacheKey) : base(serviceCallSite, cacheKey) + { + } + + public override CallSiteKind Kind { get; } = CallSiteKind.Singleton; + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ThrowHelper.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ThrowHelper.cs new file mode 100644 index 00000000000..d37893b5a73 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ThrowHelper.cs @@ -0,0 +1,17 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Runtime.CompilerServices; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class ThrowHelper + { + [MethodImpl(MethodImplOptions.NoInlining)] + internal static void ThrowObjectDisposedException() + { + throw new ObjectDisposedException(nameof(IServiceProvider)); + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/TransientCallSite.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/TransientCallSite.cs new file mode 100644 index 00000000000..905fd9e4bb7 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/TransientCallSite.cs @@ -0,0 +1,21 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + internal class TransientCallSite : IServiceCallSite + { + internal IServiceCallSite ServiceCallSite { get; } + + public TransientCallSite(IServiceCallSite serviceCallSite) + { + ServiceCallSite = serviceCallSite; + } + + public Type ServiceType => ServiceCallSite.ServiceType; + public Type ImplementationType => ServiceCallSite.ImplementationType; + public CallSiteKind Kind { get; } = CallSiteKind.Transient; + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProvider.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProvider.cs new file mode 100644 index 00000000000..690835b1b1c --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProvider.cs @@ -0,0 +1,68 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using Microsoft.Extensions.DependencyInjection.ServiceLookup; + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// The default IServiceProvider. + /// + public sealed class ServiceProvider : IServiceProvider, IDisposable, IServiceProviderEngineCallback + { + private readonly IServiceProviderEngine _engine; + + private readonly CallSiteValidator _callSiteValidator; + + internal ServiceProvider(IEnumerable serviceDescriptors, ServiceProviderOptions options) + { + IServiceProviderEngineCallback callback = null; + if (options.ValidateScopes) + { + callback = this; + _callSiteValidator = new CallSiteValidator(); + } + switch (options.Mode) + { + case ServiceProviderMode.Dynamic: + _engine = new DynamicServiceProviderEngine(serviceDescriptors, callback); + break; + case ServiceProviderMode.Runtime: + _engine = new RuntimeServiceProviderEngine(serviceDescriptors, callback); + break; +#if IL_EMIT + case ServiceProviderMode.ILEmit: + _engine = new ILEmitServiceProviderEngine(serviceDescriptors, callback); + break; +#endif + case ServiceProviderMode.Expressions: + _engine = new ExpressionsServiceProviderEngine(serviceDescriptors, callback); + break; + default: + throw new NotSupportedException(nameof(options.Mode)); + } + } + + /// + /// Gets the service object of the specified type. + /// + /// + /// + public object GetService(Type serviceType) => _engine.GetService(serviceType); + + /// + public void Dispose() => _engine.Dispose(); + + void IServiceProviderEngineCallback.OnCreate(IServiceCallSite callSite) + { + _callSiteValidator.ValidateCallSite(callSite); + } + + void IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope) + { + _callSiteValidator.ValidateResolution(serviceType, scope, _engine.RootScope); + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProviderMode.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProviderMode.cs new file mode 100644 index 00000000000..e8f3ccc7723 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProviderMode.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection +{ + internal enum ServiceProviderMode + { + Dynamic, + Runtime, + Expressions, + ILEmit + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProviderOptions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProviderOptions.cs new file mode 100644 index 00000000000..63881537e3d --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProviderOptions.cs @@ -0,0 +1,23 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// Options for configuring various behaviors of the default implementation. + /// + public class ServiceProviderOptions + { + // Avoid allocating objects in the default case + internal static readonly ServiceProviderOptions Default = new ServiceProviderOptions(); + + /// + /// true to perform check verifying that scoped services never gets resolved from root provider; otherwise false. + /// + public bool ValidateScopes { get; set; } + + internal ServiceProviderMode Mode { get; set; } = ServiceProviderMode.Dynamic; + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/baseline.netcore.json b/src/libraries/Microsoft.Extensions.DependencyInjection/src/baseline.netcore.json new file mode 100644 index 00000000000..3ab7254e039 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/baseline.netcore.json @@ -0,0 +1,412 @@ +{ + "AssemblyIdentity": "Microsoft.Extensions.DependencyInjection, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60", + "Types": [ + { + "Name": "Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.Extensions.DependencyInjection.IServiceProviderFactory" + ], + "Members": [ + { + "Kind": "Method", + "Name": "CreateBuilder", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.IServiceCollection", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.Extensions.DependencyInjection.IServiceProviderFactory", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "CreateServiceProvider", + "Parameters": [ + { + "Name": "containerBuilder", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "System.IServiceProvider", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "Microsoft.Extensions.DependencyInjection.IServiceProviderFactory", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [ + { + "Name": "options", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceProviderOptions" + } + ], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.ServiceCollection", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [ + "Microsoft.Extensions.DependencyInjection.IServiceCollection" + ], + "Members": [ + { + "Kind": "Method", + "Name": "get_Item", + "Parameters": [ + { + "Name": "index", + "Type": "System.Int32" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.Collections.Generic.IList", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_Item", + "Parameters": [ + { + "Name": "index", + "Type": "System.Int32" + }, + { + "Name": "value", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.Collections.Generic.IList", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "IndexOf", + "Parameters": [ + { + "Name": "item", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor" + } + ], + "ReturnType": "System.Int32", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.Collections.Generic.IList", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Insert", + "Parameters": [ + { + "Name": "index", + "Type": "System.Int32" + }, + { + "Name": "item", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.Collections.Generic.IList", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "RemoveAt", + "Parameters": [ + { + "Name": "index", + "Type": "System.Int32" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.Collections.Generic.IList", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_Count", + "Parameters": [], + "ReturnType": "System.Int32", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.Collections.Generic.ICollection", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "get_IsReadOnly", + "Parameters": [], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.Collections.Generic.ICollection", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Clear", + "Parameters": [], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.Collections.Generic.ICollection", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Contains", + "Parameters": [ + { + "Name": "item", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor" + } + ], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.Collections.Generic.ICollection", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "CopyTo", + "Parameters": [ + { + "Name": "array", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor[]" + }, + { + "Name": "arrayIndex", + "Type": "System.Int32" + } + ], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.Collections.Generic.ICollection", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Remove", + "Parameters": [ + { + "Name": "item", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceDescriptor" + } + ], + "ReturnType": "System.Boolean", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.Collections.Generic.ICollection", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "GetEnumerator", + "Parameters": [], + "ReturnType": "System.Collections.Generic.IEnumerator", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.Collections.Generic.IEnumerable", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions", + "Visibility": "Public", + "Kind": "Class", + "Abstract": true, + "Static": true, + "Sealed": true, + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "BuildServiceProvider", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceProvider", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "BuildServiceProvider", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "validateScopes", + "Type": "System.Boolean" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceProvider", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "BuildServiceProvider", + "Parameters": [ + { + "Name": "services", + "Type": "Microsoft.Extensions.DependencyInjection.IServiceCollection" + }, + { + "Name": "options", + "Type": "Microsoft.Extensions.DependencyInjection.ServiceProviderOptions" + } + ], + "ReturnType": "Microsoft.Extensions.DependencyInjection.ServiceProvider", + "Static": true, + "Extension": true, + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.ServiceProvider", + "Visibility": "Public", + "Kind": "Class", + "Sealed": true, + "ImplementedInterfaces": [ + "System.IServiceProvider", + "System.IDisposable", + "Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback" + ], + "Members": [ + { + "Kind": "Method", + "Name": "GetService", + "Parameters": [ + { + "Name": "serviceType", + "Type": "System.Type" + } + ], + "ReturnType": "System.Object", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.IServiceProvider", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "Dispose", + "Parameters": [], + "ReturnType": "System.Void", + "Sealed": true, + "Virtual": true, + "ImplementedInterface": "System.IDisposable", + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + }, + { + "Name": "Microsoft.Extensions.DependencyInjection.ServiceProviderOptions", + "Visibility": "Public", + "Kind": "Class", + "ImplementedInterfaces": [], + "Members": [ + { + "Kind": "Method", + "Name": "get_ValidateScopes", + "Parameters": [], + "ReturnType": "System.Boolean", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Method", + "Name": "set_ValidateScopes", + "Parameters": [ + { + "Name": "value", + "Type": "System.Boolean" + } + ], + "ReturnType": "System.Void", + "Visibility": "Public", + "GenericParameter": [] + }, + { + "Kind": "Constructor", + "Name": ".ctor", + "Parameters": [], + "Visibility": "Public", + "GenericParameter": [] + } + ], + "GenericParameters": [] + } + ] +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/CallSiteTests.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/CallSiteTests.cs new file mode 100644 index 00000000000..db3cc52c4c7 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/CallSiteTests.cs @@ -0,0 +1,324 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections; +using System.Collections.Generic; +using Microsoft.Extensions.DependencyInjection.ServiceLookup; +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; +using Xunit; + +namespace Microsoft.Extensions.DependencyInjection.Tests +{ + public class CallSiteTests + { + private static readonly CallSiteRuntimeResolver CallSiteRuntimeResolver = new CallSiteRuntimeResolver(); + + public static IEnumerable TestServiceDescriptors(ServiceLifetime lifetime) + { + Func compare; + + if (lifetime == ServiceLifetime.Transient) + { + // Expect service references to be different for transient descriptors + compare = (service1, service2) => service1 != service2; + } + else + { + // Expect service references to be the same for singleton and scoped descriptors + compare = (service1, service2) => service1 == service2; + } + + // Implementation Type Descriptor + yield return new object[] + { + new[] { new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), lifetime) }, + typeof(IFakeService), + compare, + }; + // Closed Generic Descriptor + yield return new object[] + { + new[] { new ServiceDescriptor(typeof(IFakeOpenGenericService), typeof(FakeService), lifetime) }, + typeof(IFakeOpenGenericService), + compare, + }; + // Open Generic Descriptor + yield return new object[] + { + new[] + { + new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), lifetime), + new ServiceDescriptor(typeof(IFakeOpenGenericService<>), typeof(FakeOpenGenericService<>), lifetime), + }, + typeof(IFakeOpenGenericService), + compare, + }; + // Factory Descriptor + yield return new object[] + { + new[] { new ServiceDescriptor(typeof(IFakeService), _ => new FakeService(), lifetime) }, + typeof(IFakeService), + compare, + }; + + if (lifetime == ServiceLifetime.Singleton) + { + // Instance Descriptor + yield return new object[] + { + new[] { new ServiceDescriptor(typeof(IFakeService), new FakeService()) }, + typeof(IFakeService), + compare, + }; + } + } + + [Theory] + [MemberData(nameof(TestServiceDescriptors), ServiceLifetime.Singleton)] + [MemberData(nameof(TestServiceDescriptors), ServiceLifetime.Scoped)] + [MemberData(nameof(TestServiceDescriptors), ServiceLifetime.Transient)] + public void BuiltExpressionWillReturnResolvedServiceWhenAppropriate( + ServiceDescriptor[] descriptors, Type serviceType, Func compare) + { + var provider = new DynamicServiceProviderEngine(descriptors, null); + + var callSite = provider.CallSiteFactory.CreateCallSite(serviceType, new CallSiteChain()); + var collectionCallSite = provider.CallSiteFactory.CreateCallSite(typeof(IEnumerable<>).MakeGenericType(serviceType), new CallSiteChain()); + + var compiledCallSite = CompileCallSite(callSite, provider); + var compiledCollectionCallSite = CompileCallSite(collectionCallSite, provider); + + var service1 = Invoke(callSite, provider); + var service2 = compiledCallSite(provider.Root); + var serviceEnumerator = ((IEnumerable)compiledCollectionCallSite(provider.Root)).GetEnumerator(); + + Assert.NotNull(service1); + Assert.True(compare(service1, service2)); + + // Service can be IEnumerable resolved. The IEnumerable should have exactly one element. + Assert.True(serviceEnumerator.MoveNext()); + Assert.True(compare(service1, serviceEnumerator.Current)); + Assert.False(serviceEnumerator.MoveNext()); + } + + [Fact] + public void BuiltExpressionCanResolveNestedScopedService() + { + var descriptors = new ServiceCollection(); + descriptors.AddScoped(); + descriptors.AddScoped(); + descriptors.AddScoped(); + + var provider = new DynamicServiceProviderEngine(descriptors, null); + var callSite = provider.CallSiteFactory.CreateCallSite(typeof(ServiceC), new CallSiteChain()); + var compiledCallSite = CompileCallSite(callSite, provider); + + var serviceC = (ServiceC)compiledCallSite(provider.Root); + + Assert.NotNull(serviceC.ServiceB.ServiceA); + Assert.Equal(serviceC, Invoke(callSite, provider)); + } + + [Theory] + [InlineData(ServiceLifetime.Scoped)] + [InlineData(ServiceLifetime.Transient)] + [InlineData(ServiceLifetime.Singleton)] + public void BuildExpressionAddsDisposableCaptureForDisposableServices(ServiceLifetime lifetime) + { + IServiceCollection descriptors = new ServiceCollection(); + descriptors.Add(ServiceDescriptor.Describe(typeof(ServiceA), typeof(DisposableServiceA), lifetime)); + descriptors.Add(ServiceDescriptor.Describe(typeof(ServiceB), typeof(DisposableServiceB), lifetime)); + descriptors.Add(ServiceDescriptor.Describe(typeof(ServiceC), typeof(DisposableServiceC), lifetime)); + + var disposables = new List(); + var provider = new DynamicServiceProviderEngine(descriptors, null); + provider.Root._captureDisposableCallback = obj => + { + disposables.Add(obj); + }; + var callSite = provider.CallSiteFactory.CreateCallSite(typeof(ServiceC), new CallSiteChain()); + var compiledCallSite = CompileCallSite(callSite, provider); + + var serviceC = (DisposableServiceC)compiledCallSite(provider.Root); + + Assert.Equal(3, disposables.Count); + } + + [Theory] + [InlineData(ServiceLifetime.Scoped)] + [InlineData(ServiceLifetime.Transient)] + [InlineData(ServiceLifetime.Singleton)] + public void BuildExpressionAddsDisposableCaptureForDisposableFactoryServices(ServiceLifetime lifetime) + { + IServiceCollection descriptors = new ServiceCollection(); + descriptors.Add(ServiceDescriptor.Describe(typeof(ServiceA), typeof(DisposableServiceA), lifetime)); + descriptors.Add(ServiceDescriptor.Describe(typeof(ServiceB), typeof(DisposableServiceB), lifetime)); + descriptors.Add(ServiceDescriptor.Describe( + typeof(ServiceC), p => new DisposableServiceC(p.GetService()), lifetime)); + + var disposables = new List(); + var provider = new DynamicServiceProviderEngine(descriptors, null); + provider.Root._captureDisposableCallback = obj => + { + disposables.Add(obj); + }; + var callSite = provider.CallSiteFactory.CreateCallSite(typeof(ServiceC), new CallSiteChain()); + var compiledCallSite = CompileCallSite(callSite, provider); + + var serviceC = (DisposableServiceC)compiledCallSite(provider.Root); + + Assert.Equal(3, disposables.Count); + } + + [Theory] + [InlineData(ServiceLifetime.Scoped)] + [InlineData(ServiceLifetime.Transient)] + // We are not testing singleton here because singleton resolutions always got through + // runtime resolver and there is no sense to eliminating call from there + public void BuildExpressionElidesDisposableCaptureForNonDisposableServices(ServiceLifetime lifetime) + { + IServiceCollection descriptors = new ServiceCollection(); + descriptors.Add(ServiceDescriptor.Describe(typeof(ServiceA), typeof(ServiceA), lifetime)); + descriptors.Add(ServiceDescriptor.Describe(typeof(ServiceB), typeof(ServiceB), lifetime)); + descriptors.Add(ServiceDescriptor.Describe(typeof(ServiceC), typeof(ServiceC), lifetime)); + + descriptors.AddScoped(); + descriptors.AddTransient(); + + var disposables = new List(); + var provider = new DynamicServiceProviderEngine(descriptors, null); + provider.Root._captureDisposableCallback = obj => + { + disposables.Add(obj); + }; + var callSite = provider.CallSiteFactory.CreateCallSite(typeof(ServiceC), new CallSiteChain()); + var compiledCallSite = CompileCallSite(callSite, provider); + + var serviceC = (ServiceC)compiledCallSite(provider.Root); + + Assert.Empty(disposables); + } + + [Theory] + [InlineData(ServiceLifetime.Scoped)] + [InlineData(ServiceLifetime.Transient)] + // We are not testing singleton here because singleton resolutions always got through + // runtime resolver and there is no sense to eliminating call from there + public void BuildExpressionElidesDisposableCaptureForEnumerableServices(ServiceLifetime lifetime) + { + IServiceCollection descriptors = new ServiceCollection(); + descriptors.Add(ServiceDescriptor.Describe(typeof(ServiceA), typeof(ServiceA), lifetime)); + descriptors.Add(ServiceDescriptor.Describe(typeof(ServiceD), typeof(ServiceD), lifetime)); + + var disposables = new List(); + var provider = new DynamicServiceProviderEngine(descriptors, null); + provider.Root._captureDisposableCallback = obj => + { + disposables.Add(obj); + }; + var callSite = provider.CallSiteFactory.CreateCallSite(typeof(ServiceD), new CallSiteChain()); + var compiledCallSite = CompileCallSite(callSite, provider); + + var serviceD = (ServiceD)compiledCallSite(provider.Root); + + Assert.Empty(disposables); + } + + [Fact] + public void BuiltExpressionRethrowsOriginalExceptionFromConstructor() + { + var descriptors = new ServiceCollection(); + descriptors.AddTransient(); + descriptors.AddTransient(); + descriptors.AddTransient(); + + var provider = new DynamicServiceProviderEngine(descriptors, null); + + var callSite1 = provider.CallSiteFactory.CreateCallSite(typeof(ClassWithThrowingEmptyCtor), new CallSiteChain()); + var compiledCallSite1 = CompileCallSite(callSite1, provider); + + var callSite2 = provider.CallSiteFactory.CreateCallSite(typeof(ClassWithThrowingCtor), new CallSiteChain()); + var compiledCallSite2 = CompileCallSite(callSite2, provider); + + var ex1 = Assert.Throws(() => compiledCallSite1(provider.Root)); + Assert.Equal(nameof(ClassWithThrowingEmptyCtor), ex1.Message); + + var ex2 = Assert.Throws(() => compiledCallSite2(provider.Root)); + Assert.Equal(nameof(ClassWithThrowingCtor), ex2.Message); + } + + private class ServiceD + { + public ServiceD(IEnumerable services) + { + + } + } + + private class ServiceA + { + } + + private class ServiceB + { + public ServiceB(ServiceA serviceA) + { + ServiceA = serviceA; + } + + public ServiceA ServiceA { get; set; } + } + + private class ServiceC + { + public ServiceC(ServiceB serviceB) + { + ServiceB = serviceB; + } + + public ServiceB ServiceB { get; set; } + } + + private class DisposableServiceA : ServiceA, IDisposable + { + public void Dispose() + { + } + } + + private class DisposableServiceB : ServiceB, IDisposable + { + public DisposableServiceB(ServiceA serviceA) + : base(serviceA) + { + } + + public void Dispose() + { + } + } + + private class DisposableServiceC : ServiceC, IDisposable + { + public DisposableServiceC(ServiceB serviceB) + : base(serviceB) + { + } + + public void Dispose() + { + } + } + + private static object Invoke(IServiceCallSite callSite, ServiceProviderEngine provider) + { + return CallSiteRuntimeResolver.Resolve(callSite, provider.Root); + } + + private static Func CompileCallSite(IServiceCallSite callSite, ServiceProviderEngine engine) + { + return new ExpressionResolverBuilder(CallSiteRuntimeResolver, engine, engine.Root).Build(callSite); + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/CircularDependencyTests.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/CircularDependencyTests.cs new file mode 100644 index 00000000000..fbfc9dbedff --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/CircularDependencyTests.cs @@ -0,0 +1,208 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using Microsoft.Extensions.DependencyInjection.Tests.Fakes; +using Xunit; + +namespace Microsoft.Extensions.DependencyInjection.Tests +{ + public class CircularDependencyTests + { + [Fact] + public void SelfCircularDependency() + { + var expectedMessage = "A circular dependency was detected for the service of type " + + "'Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency'." + + Environment.NewLine + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency"; + + var serviceProvider = new ServiceCollection() + .AddTransient() + .BuildServiceProvider(); + + var exception = Assert.Throws(() => + serviceProvider.GetRequiredService()); + + Assert.Equal(expectedMessage, exception.Message); + } + + [Fact] + public void SelfCircularDependencyInEnumerable() + { + var expectedMessage = "A circular dependency was detected for the service of type " + + "'Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency'." + + Environment.NewLine + + "System.Collections.Generic.IEnumerable -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency"; + + var serviceProvider = new ServiceCollection() + .AddTransient() + .BuildServiceProvider(); + + var exception = Assert.Throws(() => + serviceProvider.GetRequiredService>()); + + Assert.Equal(expectedMessage, exception.Message); + } + + [Fact] + public void SelfCircularDependencyGenericDirect() + { + var expectedMessage = "A circular dependency was detected for the service of type " + + "'Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric'." + + Environment.NewLine + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric"; + + var serviceProvider = new ServiceCollection() + .AddTransient>() + .BuildServiceProvider(); + + var exception = Assert.Throws(() => + serviceProvider.GetRequiredService>()); + + Assert.Equal(expectedMessage, exception.Message); + } + + [Fact] + public void SelfCircularDependencyGenericIndirect() + { + var expectedMessage = "A circular dependency was detected for the service of type " + + "'Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric'." + + Environment.NewLine + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric"; + + var serviceProvider = new ServiceCollection() + .AddTransient>() + .AddTransient>() + .BuildServiceProvider(); + + var exception = Assert.Throws(() => + serviceProvider.GetRequiredService>()); + + Assert.Equal(expectedMessage, exception.Message); + } + + [Fact] + public void NoCircularDependencyGeneric() + { + var serviceProvider = new ServiceCollection() + .AddSingleton(new SelfCircularDependencyGeneric()) + .AddTransient>() + .BuildServiceProvider(); + + // This will not throw because we are creating an instance of the first time + // using the parameterless constructor which has no circular dependency + var resolvedService = serviceProvider.GetRequiredService>(); + Assert.NotNull(resolvedService); + } + + [Fact] + public void SelfCircularDependencyWithInterface() + { + var expectedMessage = "A circular dependency was detected for the service of type " + + "'Microsoft.Extensions.DependencyInjection.Tests.Fakes.ISelfCircularDependencyWithInterface'." + + Environment.NewLine + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyWithInterface -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.ISelfCircularDependencyWithInterface" + + "(Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyWithInterface) -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.ISelfCircularDependencyWithInterface"; + + var serviceProvider = new ServiceCollection() + .AddTransient() + .AddTransient() + .BuildServiceProvider(); + + var exception = Assert.Throws(() => + serviceProvider.GetRequiredService()); + + Assert.Equal(expectedMessage, exception.Message); + } + + [Fact] + public void DirectCircularDependency() + { + var expectedMessage = "A circular dependency was detected for the service of type " + + "'Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA'." + + Environment.NewLine + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyB -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA"; + + var serviceProvider = new ServiceCollection() + .AddSingleton() + .AddSingleton() + .BuildServiceProvider(); + + var exception = Assert.Throws(() => + serviceProvider.GetRequiredService()); + + Assert.Equal(expectedMessage, exception.Message); + } + + [Fact] + public void IndirectCircularDependency() + { + var expectedMessage = "A circular dependency was detected for the service of type " + + "'Microsoft.Extensions.DependencyInjection.Tests.Fakes.IndirectCircularDependencyA'." + + Environment.NewLine + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.IndirectCircularDependencyA -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.IndirectCircularDependencyB -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.IndirectCircularDependencyC -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.IndirectCircularDependencyA"; + + var serviceProvider = new ServiceCollection() + .AddSingleton() + .AddTransient() + .AddTransient() + .BuildServiceProvider(); + + var exception = Assert.Throws(() => + serviceProvider.GetRequiredService()); + + Assert.Equal(expectedMessage, exception.Message); + } + + [Fact] + public void NoCircularDependencySameTypeMultipleTimes() + { + var serviceProvider = new ServiceCollection() + .AddTransient() + .AddTransient() + .AddTransient() + .BuildServiceProvider(); + + var resolvedService = serviceProvider.GetRequiredService(); + Assert.NotNull(resolvedService); + } + + [Fact] + public void DependencyOnCircularDependency() + { + var expectedMessage = "A circular dependency was detected for the service of type " + + "'Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA'." + + Environment.NewLine + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.DependencyOnCircularDependency -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyB -> " + + "Microsoft.Extensions.DependencyInjection.Tests.Fakes.DirectCircularDependencyA"; + + var serviceProvider = new ServiceCollection() + .AddTransient() + .AddTransient() + .AddTransient() + .BuildServiceProvider(); + + var exception = Assert.Throws(() => + serviceProvider.GetRequiredService()); + + Assert.Equal(expectedMessage, exception.Message); + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/AbstractClass.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/AbstractClass.cs new file mode 100644 index 00000000000..cebe321659a --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/AbstractClass.cs @@ -0,0 +1,12 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public abstract class AbstractClass + { + public AbstractClass() + { + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/DependencyOnCircularDependency.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/DependencyOnCircularDependency.cs new file mode 100644 index 00000000000..9c2d5745ff5 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/DependencyOnCircularDependency.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public class DependencyOnCircularDependency + { + public DependencyOnCircularDependency(DirectCircularDependencyA a) + { + + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/DirectCircularDependencyA.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/DirectCircularDependencyA.cs new file mode 100644 index 00000000000..003c55ec1d0 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/DirectCircularDependencyA.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public class DirectCircularDependencyA + { + public DirectCircularDependencyA(DirectCircularDependencyB b) + { + + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/DirectCircularDependencyB.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/DirectCircularDependencyB.cs new file mode 100644 index 00000000000..2a275798cc9 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/DirectCircularDependencyB.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public class DirectCircularDependencyB + { + public DirectCircularDependencyB(DirectCircularDependencyA a) + { + + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/ISelfCircularDependencyWithInterface.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/ISelfCircularDependencyWithInterface.cs new file mode 100644 index 00000000000..c43a4eaa614 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/ISelfCircularDependencyWithInterface.cs @@ -0,0 +1,9 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public interface ISelfCircularDependencyWithInterface + { + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/IndirectCircularDependencyA.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/IndirectCircularDependencyA.cs new file mode 100644 index 00000000000..ecfb8363236 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/IndirectCircularDependencyA.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public class IndirectCircularDependencyA + { + public IndirectCircularDependencyA(IndirectCircularDependencyB b) + { + + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/IndirectCircularDependencyB.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/IndirectCircularDependencyB.cs new file mode 100644 index 00000000000..f4687058f2f --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/IndirectCircularDependencyB.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public class IndirectCircularDependencyB + { + public IndirectCircularDependencyB(IndirectCircularDependencyC c) + { + + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/IndirectCircularDependencyC.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/IndirectCircularDependencyC.cs new file mode 100644 index 00000000000..fb58f2c69bb --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/IndirectCircularDependencyC.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public class IndirectCircularDependencyC + { + public IndirectCircularDependencyC(IndirectCircularDependencyA a) + { + + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/NoCircularDependencySameTypeMultipleTimesA.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/NoCircularDependencySameTypeMultipleTimesA.cs new file mode 100644 index 00000000000..adbf3e45940 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/NoCircularDependencySameTypeMultipleTimesA.cs @@ -0,0 +1,21 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + // A + // / | \ + // B C C + // | + // C + public class NoCircularDependencySameTypeMultipleTimesA + { + public NoCircularDependencySameTypeMultipleTimesA( + NoCircularDependencySameTypeMultipleTimesB b, + NoCircularDependencySameTypeMultipleTimesC c1, + NoCircularDependencySameTypeMultipleTimesC c2) + { + + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/NoCircularDependencySameTypeMultipleTimesB.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/NoCircularDependencySameTypeMultipleTimesB.cs new file mode 100644 index 00000000000..8bb0a34205d --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/NoCircularDependencySameTypeMultipleTimesB.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public class NoCircularDependencySameTypeMultipleTimesB + { + public NoCircularDependencySameTypeMultipleTimesB(NoCircularDependencySameTypeMultipleTimesC c) + { + + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/NoCircularDependencySameTypeMultipleTimesC.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/NoCircularDependencySameTypeMultipleTimesC.cs new file mode 100644 index 00000000000..93a6fd298a0 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/NoCircularDependencySameTypeMultipleTimesC.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public class NoCircularDependencySameTypeMultipleTimesC + { + public NoCircularDependencySameTypeMultipleTimesC() + { + + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/SelfCircularDependency.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/SelfCircularDependency.cs new file mode 100644 index 00000000000..16d84561549 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/SelfCircularDependency.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public class SelfCircularDependency + { + public SelfCircularDependency(SelfCircularDependency self) + { + + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/SelfCircularDependencyGeneric.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/SelfCircularDependencyGeneric.cs new file mode 100644 index 00000000000..c6f953e1a21 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/SelfCircularDependencyGeneric.cs @@ -0,0 +1,18 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public class SelfCircularDependencyGeneric + { + public SelfCircularDependencyGeneric(SelfCircularDependencyGeneric dependency) + { + + } + + public SelfCircularDependencyGeneric() + { + + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/SelfCircularDependencyWithInterface.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/SelfCircularDependencyWithInterface.cs new file mode 100644 index 00000000000..344995cd097 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/CircularReferences/SelfCircularDependencyWithInterface.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public class SelfCircularDependencyWithInterface : ISelfCircularDependencyWithInterface + { + public SelfCircularDependencyWithInterface(ISelfCircularDependencyWithInterface self) + { + + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/ClassDependsOnPrivateConstructorClass.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/ClassDependsOnPrivateConstructorClass.cs new file mode 100644 index 00000000000..c650a9ea458 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/ClassDependsOnPrivateConstructorClass.cs @@ -0,0 +1,15 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public class ClassDependsOnPrivateConstructorClass + { + public ClassDependsOnPrivateConstructorClass(ClassWithPrivateCtor value) + { + + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/ClassWithNestedReferencesToProvider.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/ClassWithNestedReferencesToProvider.cs new file mode 100644 index 00000000000..a1d45bafe00 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/ClassWithNestedReferencesToProvider.cs @@ -0,0 +1,34 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public class ClassWithNestedReferencesToProvider : IDisposable + { + private IServiceProvider _serviceProvider; + private ClassWithNestedReferencesToProvider _nested; + + public ClassWithNestedReferencesToProvider(IServiceProvider serviceProvider) + { + _serviceProvider = serviceProvider; + _nested = new ClassWithNestedReferencesToProvider(_serviceProvider, 0); + } + + private ClassWithNestedReferencesToProvider(IServiceProvider serviceProvider, int level) + { + _serviceProvider = serviceProvider; + if (level > 1) + { + _nested = new ClassWithNestedReferencesToProvider(_serviceProvider, level + 1); + } + } + + public void Dispose() + { + _nested?.Dispose(); + (_serviceProvider as IDisposable)?.Dispose(); + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/ClassWithOptionalArgsCtorWithStructs.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/ClassWithOptionalArgsCtorWithStructs.cs new file mode 100644 index 00000000000..d512d8dc151 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/ClassWithOptionalArgsCtorWithStructs.cs @@ -0,0 +1,28 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; + +namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes +{ + public class ClassWithServiceAndOptionalArgsCtorWithStructs + { + public ClassWithServiceAndOptionalArgsCtorWithStructs(IFakeService fake, + DateTime dateTime = new DateTime(), + DateTime dateTimeDefault = default(DateTime), + TimeSpan timeSpan = new TimeSpan(), + TimeSpan timeSpanDefault = default(TimeSpan), + DateTimeOffset dateTimeOffset = new DateTimeOffset(), + DateTimeOffset dateTimeOffsetDefault = default(DateTimeOffset), + Guid guid = new Guid(), + Guid guidDefault = default(Guid), + CustomStruct customStruct = new CustomStruct(), + CustomStruct customStructDefault = default(CustomStruct) + ) + { + } + + public struct CustomStruct { } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/DependOnNonexistentService.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/DependOnNonexistentService.cs new file mode 100644 index 00000000000..af2e937e250 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/DependOnNonexistentService.cs @@ -0,0 +1,14 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; + +namespace Microsoft.Extensions.DependencyInjection.Tests +{ + public class DependOnNonexistentService + { + public DependOnNonexistentService(IFakeService nonExistentService) + { + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/StructFakeMultipleService.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/StructFakeMultipleService.cs new file mode 100644 index 00000000000..d1cd255a099 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/StructFakeMultipleService.cs @@ -0,0 +1,11 @@ +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; + +namespace Microsoft.Extensions.DependencyInjection.Fakes +{ + public struct StructFakeMultipleService : IFakeMultipleService + { + public StructFakeMultipleService(IFakeService service, StructService direct) + { + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/StructFakeService.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/StructFakeService.cs new file mode 100644 index 00000000000..e4ad356163d --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/StructFakeService.cs @@ -0,0 +1,12 @@ +using System; +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; + +namespace Microsoft.Extensions.DependencyInjection.Fakes +{ + public struct StructFakeService : IFakeService + { + public StructFakeService(IServiceProvider serviceProvider) + { + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/StructService.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/StructService.cs new file mode 100644 index 00000000000..0fdb383ebb0 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Fakes/StructService.cs @@ -0,0 +1,9 @@ +namespace Microsoft.Extensions.DependencyInjection.Fakes +{ + public struct StructService + { + public StructService(IServiceScopeFactory scopeFactory) + { + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Microsoft.Extensions.DependencyInjection.Tests.csproj b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Microsoft.Extensions.DependencyInjection.Tests.csproj new file mode 100644 index 00000000000..131014e83b6 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Microsoft.Extensions.DependencyInjection.Tests.csproj @@ -0,0 +1,21 @@ + + + + $(StandardTestTfms) + Microsoft.Extensions.DependencyInjection + + + + + + + + + + + + + + + + diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceCollectionDescriptorExtensionsTests.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceCollectionDescriptorExtensionsTests.cs new file mode 100644 index 00000000000..2bf26900bf9 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceCollectionDescriptorExtensionsTests.cs @@ -0,0 +1,62 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; +using Xunit; + +namespace Microsoft.Extensions.DependencyInjection +{ + public class ServiceCollectionDescriptorExtensionsTest + { + [Fact] + public void Add_AddsDescriptorToServiceDescriptors() + { + // Arrange + var serviceCollection = new ServiceCollection(); + var descriptor = new ServiceDescriptor(typeof(IFakeService), new FakeService()); + + // Act + serviceCollection.Add(descriptor); + + // Assert + var result = Assert.Single(serviceCollection); + Assert.Same(result, descriptor); + } + + [Fact] + public void Add_AddsMultipleDescriptorToServiceDescriptors() + { + // Arrange + var serviceCollection = new ServiceCollection(); + var descriptor1 = new ServiceDescriptor(typeof(IFakeService), new FakeService()); + var descriptor2 = new ServiceDescriptor(typeof(IFactoryService), typeof(TransientFactoryService), ServiceLifetime.Transient); + + // Act + serviceCollection.Add(descriptor1); + serviceCollection.Add(descriptor2); + + // Assert + Assert.Equal(2, serviceCollection.Count); + Assert.Equal(new[] { descriptor1, descriptor2 }, serviceCollection); + } + + [Fact] + public void ServiceDescriptors_AllowsRemovingPreviousRegisteredServices() + { + // Arrange + var serviceCollection = new ServiceCollection(); + var descriptor1 = new ServiceDescriptor(typeof(IFakeService), new FakeService()); + var descriptor2 = new ServiceDescriptor(typeof(IFactoryService), typeof(TransientFactoryService), ServiceLifetime.Transient); + + // Act + serviceCollection.Add(descriptor1); + serviceCollection.Add(descriptor2); + serviceCollection.Remove(descriptor1); + + // Assert + var result = Assert.Single(serviceCollection); + Assert.Same(result, descriptor2); + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceCollectionServiceExtensionsTest.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceCollectionServiceExtensionsTest.cs new file mode 100644 index 00000000000..c38889f5e22 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceCollectionServiceExtensionsTest.cs @@ -0,0 +1,424 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using Microsoft.AspNetCore.Testing; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; +using Xunit; + +using AbstractionResources = Microsoft.Extensions.DependencyInjection.Abstractions.Resources; + +namespace Microsoft.Extensions.DependencyInjection +{ + public class ServiceCollectionServiceExtensionsTest + { + private static readonly FakeService _instance = new FakeService(); + + public static TheoryData AddImplementationTypeData + { + get + { + var serviceType = typeof(IFakeService); + var implementationType = typeof(FakeService); + return new TheoryData, Type, Type, ServiceLifetime> + { + { collection => collection.AddTransient(serviceType, implementationType), serviceType, implementationType, ServiceLifetime.Transient }, + { collection => collection.AddTransient(), serviceType, implementationType, ServiceLifetime.Transient }, + { collection => collection.AddTransient(), serviceType, serviceType, ServiceLifetime.Transient }, + { collection => collection.AddTransient(implementationType), implementationType, implementationType, ServiceLifetime.Transient }, + + { collection => collection.AddScoped(serviceType, implementationType), serviceType, implementationType, ServiceLifetime.Scoped }, + { collection => collection.AddScoped(), serviceType, implementationType, ServiceLifetime.Scoped }, + { collection => collection.AddScoped(), serviceType, serviceType, ServiceLifetime.Scoped }, + { collection => collection.AddScoped(implementationType), implementationType, implementationType, ServiceLifetime.Scoped }, + + { collection => collection.AddSingleton(serviceType, implementationType), serviceType, implementationType, ServiceLifetime.Singleton }, + { collection => collection.AddSingleton(), serviceType, implementationType, ServiceLifetime.Singleton }, + { collection => collection.AddSingleton(), serviceType, serviceType, ServiceLifetime.Singleton }, + { collection => collection.AddSingleton(implementationType), implementationType, implementationType, ServiceLifetime.Singleton }, + }; + } + } + + [Theory] + [MemberData(nameof(AddImplementationTypeData))] + public void AddWithTypeAddsServiceWithRightLifecyle(Action addTypeAction, + Type expectedServiceType, + Type expectedImplementationType, + ServiceLifetime lifeCycle) + { + // Arrange + var collection = new ServiceCollection(); + + // Act + addTypeAction(collection); + + // Assert + var descriptor = Assert.Single(collection); + Assert.Equal(expectedServiceType, descriptor.ServiceType); + Assert.Equal(expectedImplementationType, descriptor.ImplementationType); + Assert.Equal(lifeCycle, descriptor.Lifetime); + } + + public static TheoryData AddImplementationFactoryData + { + get + { + var serviceType = typeof(IFakeService); + var implementationType = typeof(FakeService); + var objectType = typeof(object); + + return new TheoryData, Type, Type, ServiceLifetime> + { + { collection => collection.AddTransient(serviceType, s => new FakeService()), serviceType, objectType, ServiceLifetime.Transient }, + { collection => collection.AddTransient(s => new FakeService()), serviceType, serviceType, ServiceLifetime.Transient }, + { collection => collection.AddTransient(s => new FakeService()), serviceType, implementationType, ServiceLifetime.Transient }, + + { collection => collection.AddScoped(serviceType, s => new FakeService()), serviceType, objectType, ServiceLifetime.Scoped }, + { collection => collection.AddScoped(s => new FakeService()), serviceType, serviceType, ServiceLifetime.Scoped }, + { collection => collection.AddScoped(s => new FakeService()), serviceType, implementationType, ServiceLifetime.Scoped }, + + { collection => collection.AddSingleton(serviceType, s => new FakeService()), serviceType, objectType, ServiceLifetime.Singleton }, + { collection => collection.AddSingleton(s => new FakeService()), serviceType, serviceType, ServiceLifetime.Singleton }, + { collection => collection.AddSingleton(s => new FakeService()), serviceType, implementationType, ServiceLifetime.Singleton }, + }; + } + } + + [Theory] + [MemberData(nameof(AddImplementationFactoryData))] + public void AddWithFactoryAddsServiceWithRightLifecyle( + Action addAction, + Type serviceType, + Type implementationType, + ServiceLifetime lifeCycle) + { + // Arrange + var collection = new ServiceCollection(); + + // Act + addAction(collection); + + // Assert + var descriptor = Assert.Single(collection); + Assert.Equal(serviceType, descriptor.ServiceType); + Assert.Equal(implementationType, descriptor.GetImplementationType()); + Assert.Equal(lifeCycle, descriptor.Lifetime); + } + + public static TheoryData AddSingletonData + { + get + { + return new TheoryData> + { + { collection => collection.AddSingleton(_instance) }, + { collection => collection.AddSingleton(typeof(IFakeService), _instance) }, + }; + } + } + + [Theory] + [MemberData(nameof(AddSingletonData))] + public void AddSingleton_AddsWithSingletonLifecycle(Action addAction) + { + // Arrange + var collection = new ServiceCollection(); + + // Act + addAction(collection); + + // Assert + var descriptor = Assert.Single(collection); + Assert.Equal(typeof(IFakeService), descriptor.ServiceType); + Assert.Same(_instance, descriptor.ImplementationInstance); + Assert.Equal(ServiceLifetime.Singleton, descriptor.Lifetime); + } + + [Theory] + [MemberData(nameof(AddSingletonData))] + public void TryAddNoOpFailsIfExists(Action addAction) + { + // Arrange + var collection = new ServiceCollection(); + addAction(collection); + var d = ServiceDescriptor.Transient(); + + // Act + collection.TryAdd(d); + + // Assert + var descriptor = Assert.Single(collection); + Assert.Equal(typeof(IFakeService), descriptor.ServiceType); + Assert.Same(_instance, descriptor.ImplementationInstance); + Assert.Equal(ServiceLifetime.Singleton, descriptor.Lifetime); + } + + public static TheoryData TryAddImplementationTypeData + { + get + { + var serviceType = typeof(IFakeService); + var implementationType = typeof(FakeService); + return new TheoryData, Type, Type, ServiceLifetime> + { + { collection => collection.TryAddTransient(serviceType, implementationType), serviceType, implementationType, ServiceLifetime.Transient }, + { collection => collection.TryAddTransient(), serviceType, implementationType, ServiceLifetime.Transient }, + { collection => collection.TryAddTransient(), serviceType, serviceType, ServiceLifetime.Transient }, + { collection => collection.TryAddTransient(implementationType), implementationType, implementationType, ServiceLifetime.Transient }, + + { collection => collection.TryAddScoped(serviceType, implementationType), serviceType, implementationType, ServiceLifetime.Scoped }, + { collection => collection.TryAddScoped(), serviceType, implementationType, ServiceLifetime.Scoped }, + { collection => collection.TryAddScoped(), serviceType, serviceType, ServiceLifetime.Scoped }, + { collection => collection.TryAddScoped(implementationType), implementationType, implementationType, ServiceLifetime.Scoped }, + + { collection => collection.TryAddSingleton(serviceType, implementationType), serviceType, implementationType, ServiceLifetime.Singleton }, + { collection => collection.TryAddSingleton(), serviceType, implementationType, ServiceLifetime.Singleton }, + { collection => collection.TryAddSingleton(), serviceType, serviceType, ServiceLifetime.Singleton }, + { collection => collection.TryAddSingleton(implementationType), implementationType, implementationType, ServiceLifetime.Singleton }, + }; + } + } + + [Theory] + [MemberData(nameof(TryAddImplementationTypeData))] + public void TryAdd_WithType_AddsService( + Action addAction, + Type expectedServiceType, + Type expectedImplementationType, + ServiceLifetime expectedLifetime) + { + // Arrange + var collection = new ServiceCollection(); + + // Act + addAction(collection); + + // Assert + var descriptor = Assert.Single(collection); + Assert.Equal(expectedServiceType, descriptor.ServiceType); + Assert.Same(expectedImplementationType, descriptor.ImplementationType); + Assert.Equal(expectedLifetime, descriptor.Lifetime); + } + + [Theory] + [MemberData(nameof(TryAddImplementationTypeData))] + public void TryAdd_WithType_DoesNotAddDuplicate( + Action addAction, + Type expectedServiceType, + // Test verifies that descriptor is not added so we don't need to assert it's properties +#pragma warning disable xUnit1026 + Type expectedImplementationType, + ServiceLifetime expectedLifetime +#pragma warning restore xUnit1026 + ) + { + // Arrange + var collection = new ServiceCollection + { + ServiceDescriptor.Transient(expectedServiceType, expectedServiceType) + }; + + // Act + addAction(collection); + + // Assert + var descriptor = Assert.Single(collection); + Assert.Equal(expectedServiceType, descriptor.ServiceType); + Assert.Same(expectedServiceType, descriptor.ImplementationType); + Assert.Equal(ServiceLifetime.Transient, descriptor.Lifetime); + } + + [Fact] + public void TryAddIfMissingActuallyAdds() + { + // Arrange + var collection = new ServiceCollection(); + var d = ServiceDescriptor.Transient(); + + // Act + collection.TryAdd(d); + + // Assert + var descriptor = Assert.Single(collection); + Assert.Equal(typeof(IFakeService), descriptor.ServiceType); + Assert.Null(descriptor.ImplementationInstance); + Assert.Equal(ServiceLifetime.Transient, descriptor.Lifetime); + } + + public static TheoryData TryAddEnumerableImplementationTypeData + { + get + { + var serviceType = typeof(IFakeService); + var implementationType = typeof(FakeService); + return new TheoryData + { + { ServiceDescriptor.Transient(), serviceType, implementationType, ServiceLifetime.Transient }, + { ServiceDescriptor.Transient(s => new FakeService()), serviceType, implementationType, ServiceLifetime.Transient }, + + { ServiceDescriptor.Scoped(), serviceType, implementationType, ServiceLifetime.Scoped }, + { ServiceDescriptor.Scoped(s => new FakeService()), serviceType, implementationType, ServiceLifetime.Scoped }, + + { ServiceDescriptor.Singleton(), serviceType, implementationType, ServiceLifetime.Singleton }, + { ServiceDescriptor.Singleton(s => new FakeService()), serviceType, implementationType, ServiceLifetime.Singleton }, + + { ServiceDescriptor.Singleton(_instance), serviceType, implementationType, ServiceLifetime.Singleton }, + }; + } + } + + [Theory] + [MemberData(nameof(TryAddEnumerableImplementationTypeData))] + public void TryAddEnumerable_AddsService( + ServiceDescriptor descriptor, + Type expectedServiceType, + Type expectedImplementationType, + ServiceLifetime expectedLifetime) + { + // Arrange + var collection = new ServiceCollection(); + + // Act + collection.TryAddEnumerable(descriptor); + + // Assert + var d = Assert.Single(collection); + Assert.Equal(expectedServiceType, d.ServiceType); + Assert.Equal(expectedImplementationType, d.GetImplementationType()); + Assert.Equal(expectedLifetime, d.Lifetime); + } + + + [Theory] + [MemberData(nameof(TryAddEnumerableImplementationTypeData))] + public void TryAddEnumerable_DoesNotAddDuplicate( + ServiceDescriptor descriptor, + Type expectedServiceType, + Type expectedImplementationType, + ServiceLifetime expectedLifetime) + { + // Arrange + var collection = new ServiceCollection(); + collection.TryAddEnumerable(descriptor); + + // Act + collection.TryAddEnumerable(descriptor); + + // Assert + var d = Assert.Single(collection); + Assert.Equal(expectedServiceType, d.ServiceType); + Assert.Equal(expectedImplementationType, d.GetImplementationType()); + Assert.Equal(expectedLifetime, d.Lifetime); + } + + public static TheoryData TryAddEnumerableInvalidImplementationTypeData + { + get + { + var serviceType = typeof(IFakeService); + var implementationType = typeof(FakeService); + var objectType = typeof(object); + + return new TheoryData + { + { ServiceDescriptor.Transient(s => new FakeService()), serviceType, serviceType }, + { ServiceDescriptor.Transient(serviceType, s => new FakeService()), serviceType, objectType }, + + { ServiceDescriptor.Scoped(s => new FakeService()), serviceType, serviceType }, + { ServiceDescriptor.Scoped(serviceType, s => new FakeService()), serviceType, objectType }, + + { ServiceDescriptor.Singleton(s => new FakeService()), serviceType, serviceType }, + { ServiceDescriptor.Singleton(serviceType, s => new FakeService()), serviceType, objectType }, + }; + } + } + + [Theory] + [MemberData(nameof(TryAddEnumerableInvalidImplementationTypeData))] + public void TryAddEnumerable_ThrowsWhenAddingIndistinguishableImplementationType( + ServiceDescriptor descriptor, + Type serviceType, + Type implementationType) + { + // Arrange + var collection = new ServiceCollection(); + + // Act & Assert + ExceptionAssert.ThrowsArgument( + () => collection.TryAddEnumerable(descriptor), + "descriptor", + AbstractionResources.FormatTryAddIndistinguishableTypeToEnumerable(implementationType, serviceType)); + } + + [Fact] + public void AddSequence_AddsServicesToCollection() + { + // Arrange + var collection = new ServiceCollection(); + var descriptor1 = new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient); + var descriptor2 = new ServiceDescriptor(typeof(IFakeOuterService), typeof(FakeOuterService), ServiceLifetime.Transient); + var descriptors = new[] { descriptor1, descriptor2 }; + + // Act + var result = collection.Add(descriptors); + + // Assert + Assert.Equal(descriptors, collection); + } + + [Fact] + public void Replace_AddsServiceIfServiceTypeIsNotRegistered() + { + // Arrange + var collection = new ServiceCollection(); + var descriptor1 = new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient); + var descriptor2 = new ServiceDescriptor(typeof(IFakeOuterService), typeof(FakeOuterService), ServiceLifetime.Transient); + collection.Add(descriptor1); + + // Act + collection.Replace(descriptor2); + + // Assert + Assert.Equal(new[] { descriptor1, descriptor2 }, collection); + } + + [Fact] + public void Replace_ReplacesFirstServiceWithMatchingServiceType() + { + // Arrange + var collection = new ServiceCollection(); + var descriptor1 = new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient); + var descriptor2 = new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient); + collection.Add(descriptor1); + collection.Add(descriptor2); + var descriptor3 = new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Singleton); + + // Act + collection.Replace(descriptor3); + + // Assert + Assert.Equal(new[] { descriptor2, descriptor3 }, collection); + } + + [Fact] + public void RemoveAll_RemovesAllServicesWithMatchingServiceType() + { + // Arrange + var descriptor = new ServiceDescriptor(typeof(IFakeServiceInstance), typeof(FakeService), ServiceLifetime.Transient); + var collection = new ServiceCollection + { + descriptor, + new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient) + }; + + // Act + collection.RemoveAll(); + + // Assert + Assert.Equal(new[] { descriptor }, collection); + } + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/CallSiteFactoryTest.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/CallSiteFactoryTest.cs new file mode 100644 index 00000000000..72566be92fc --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/CallSiteFactoryTest.cs @@ -0,0 +1,426 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; +using Xunit; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + public class CallSiteFactoryTest + { + [Fact] + public void CreateCallSite_Throws_IfTypeHasNoPublicConstructors() + { + // Arrange + var type = typeof(TypeWithNoPublicConstructors); + var expectedMessage = $"A suitable constructor for type '{type}' could not be located. " + + "Ensure the type is concrete and services are registered for all parameters of a public constructor."; + var descriptor = new ServiceDescriptor(type, type, ServiceLifetime.Transient); + var callSiteFactory = GetCallSiteFactory(descriptor); + + // Act and Assert + var ex = Assert.Throws(() => callSiteFactory(type)); + Assert.Equal(expectedMessage, ex.Message); + } + + [Theory] + [InlineData(typeof(TypeWithNoConstructors))] + [InlineData(typeof(TypeWithParameterlessConstructor))] + [InlineData(typeof(TypeWithParameterlessPublicConstructor))] + public void CreateCallSite_CreatesInstanceCallSite_IfTypeHasDefaultOrPublicParameterlessConstructor(Type type) + { + // Arrange + var descriptor = new ServiceDescriptor(type, type, ServiceLifetime.Transient); + var callSiteFactory = GetCallSiteFactory(descriptor); + + // Act + var callSite = callSiteFactory(type); + + // Assert + var transientCall = Assert.IsType(callSite); + Assert.IsType(transientCall.ServiceCallSite); + } + + [Theory] + [InlineData(typeof(TypeWithParameterizedConstructor))] + [InlineData(typeof(TypeWithParameterizedAndNullaryConstructor))] + [InlineData(typeof(TypeWithMultipleParameterizedConstructors))] + [InlineData(typeof(TypeWithSupersetConstructors))] + public void CreateCallSite_CreatesConstructorCallSite_IfTypeHasConstructorWithInjectableParameters(Type type) + { + // Arrange + var descriptor = new ServiceDescriptor(type, type, ServiceLifetime.Transient); + + var callSiteFactory = GetCallSiteFactory( + descriptor, + new ServiceDescriptor(typeof(IFakeService), new FakeService()) + ); + + // Act + var callSite = callSiteFactory(type); + + // Assert + var transientCall = Assert.IsType(callSite); + var constructorCallSite = Assert.IsType(transientCall.ServiceCallSite); + Assert.Equal(new[] { typeof(IFakeService) }, GetParameters(constructorCallSite)); + } + + [Fact] + public void CreateCallSite_CreatesConstructorWithEnumerableParameters() + { + // Arrange + var type = typeof(TypeWithEnumerableConstructors); + var descriptor = new ServiceDescriptor(type, type, ServiceLifetime.Transient); + + var callSiteFactory = GetCallSiteFactory( + descriptor, + new ServiceDescriptor(typeof(IFakeService), new FakeService()) + ); + + // Act + var callSite = callSiteFactory(type); + + // Assert + var transientCall = Assert.IsType(callSite); + var constructorCallSite = Assert.IsType(transientCall.ServiceCallSite); + Assert.Equal( + new[] { typeof(IEnumerable), typeof(IEnumerable) }, + GetParameters(constructorCallSite)); + } + + [Fact] + public void CreateCallSite_UsesNullaryConstructorIfServicesCannotBeInjectedIntoOtherConstructors() + { + // Arrange + var type = typeof(TypeWithParameterizedAndNullaryConstructor); + var descriptor = new ServiceDescriptor(type, type, ServiceLifetime.Transient); + var callSiteFactory = GetCallSiteFactory(descriptor); + + // Act + var callSite = callSiteFactory(type); + + // Assert + var transientCall = Assert.IsType(callSite); + Assert.IsType(transientCall.ServiceCallSite); + } + + public static TheoryData CreateCallSite_PicksConstructorWithTheMostNumberOfResolvedParametersData => + new TheoryData, Type[]> + { + { + typeof(TypeWithSupersetConstructors), + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithSupersetConstructors), typeof(TypeWithSupersetConstructors), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeService), typeof(FakeService)) + ), + new[] { typeof(IFakeService) } + }, + { + typeof(TypeWithSupersetConstructors), + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithSupersetConstructors), typeof(TypeWithSupersetConstructors), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFactoryService), typeof(TransientFactoryService)) + ), + new[] { typeof(IFactoryService) } + }, + { + typeof(TypeWithSupersetConstructors), + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithSupersetConstructors), typeof(TypeWithSupersetConstructors), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeService), typeof(FakeService)), + new ServiceDescriptor(typeof(IFactoryService), typeof(TransientFactoryService)) + ), + new[] { typeof(IFakeService), typeof(IFactoryService) } + }, + { + typeof(TypeWithSupersetConstructors), + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithSupersetConstructors), typeof(TypeWithSupersetConstructors), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeMultipleService), typeof(FakeService)), + new ServiceDescriptor(typeof(IFakeService), typeof(FakeService)), + new ServiceDescriptor(typeof(IFactoryService), typeof(TransientFactoryService)) + ), + new[] { typeof(IFakeService), typeof(IFakeMultipleService), typeof(IFactoryService) } + }, + { + typeof(TypeWithSupersetConstructors), + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithSupersetConstructors), typeof(TypeWithSupersetConstructors), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeMultipleService), typeof(FakeService)), + new ServiceDescriptor(typeof(IFakeService), typeof(FakeService)), + new ServiceDescriptor(typeof(IFactoryService), typeof(TransientFactoryService)), + new ServiceDescriptor(typeof(IFakeScopedService), typeof(FakeService)) + ), + new[] { typeof(IFakeMultipleService), typeof(IFactoryService), typeof(IFakeService), typeof(IFakeScopedService) } + }, + { + typeof(TypeWithSupersetConstructors), + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithSupersetConstructors), typeof(TypeWithSupersetConstructors), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeMultipleService), typeof(FakeService)), + new ServiceDescriptor(typeof(IFakeService), typeof(FakeService)), + new ServiceDescriptor(typeof(IFactoryService), typeof(TransientFactoryService)), + new ServiceDescriptor(typeof(IFakeScopedService), typeof(FakeService)) + ), + new[] { typeof(IFakeMultipleService), typeof(IFactoryService), typeof(IFakeService), typeof(IFakeScopedService) } + }, + { + typeof(TypeWithGenericServices), + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithGenericServices), typeof(TypeWithGenericServices), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeOpenGenericService<>), typeof(FakeOpenGenericService<>), ServiceLifetime.Transient) + ), + new[] { typeof(IFakeService), typeof(IFakeOpenGenericService) } + }, + { + typeof(TypeWithGenericServices), + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithGenericServices), typeof(TypeWithGenericServices), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeOpenGenericService<>), typeof(FakeOpenGenericService<>), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFactoryService), typeof(FakeService), ServiceLifetime.Transient) + ), + new[] { typeof(IFakeService), typeof(IFactoryService), typeof(IFakeOpenGenericService) } + } + }; + + [Theory] + [MemberData(nameof(CreateCallSite_PicksConstructorWithTheMostNumberOfResolvedParametersData))] + public void CreateCallSite_PicksConstructorWithTheMostNumberOfResolvedParameters( + Type type, + Func callSiteFactory, + Type[] expectedConstructorParameters) + { + // Act + var callSite = callSiteFactory(type); + + // Assert + var transientCall = Assert.IsType(callSite); + var constructorCallSite = Assert.IsType(transientCall.ServiceCallSite); + Assert.Equal(expectedConstructorParameters, GetParameters(constructorCallSite)); + } + + public static TheoryData CreateCallSite_ConsidersConstructorsWithDefaultValuesData => + new TheoryData, Type[]> + { + { + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithDefaultConstructorParameters), typeof(TypeWithDefaultConstructorParameters), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeMultipleService), typeof(FakeService), ServiceLifetime.Transient) + ), + new[] { typeof(IFakeMultipleService), typeof(IFakeService) } + }, + { + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithDefaultConstructorParameters), typeof(TypeWithDefaultConstructorParameters), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFactoryService), typeof(FakeService), ServiceLifetime.Transient) + ), + new[] { typeof(IFactoryService), typeof(IFakeScopedService) } + }, + { + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithDefaultConstructorParameters), typeof(TypeWithDefaultConstructorParameters), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeScopedService), typeof(FakeService), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFactoryService), typeof(FakeService), ServiceLifetime.Transient) + ), + new[] { typeof(IFactoryService), typeof(IFakeScopedService) } + } + }; + + [Theory] + [MemberData(nameof(CreateCallSite_ConsidersConstructorsWithDefaultValuesData))] + public void CreateCallSite_ConsidersConstructorsWithDefaultValues( + Func callSiteFactory, + Type[] expectedConstructorParameters) + { + // Arrange + var type = typeof(TypeWithDefaultConstructorParameters); + + // Act + var callSite = callSiteFactory(type); + + // Assert + var transientCall = Assert.IsType(callSite); + var constructorCallSite = Assert.IsType(transientCall.ServiceCallSite); + Assert.Equal(expectedConstructorParameters, GetParameters(constructorCallSite)); + } + + [Fact] + public void CreateCallSite_ThrowsIfTypeHasSingleConstructorWithUnresolvableParameters() + { + // Arrange + var type = typeof(TypeWithParameterizedConstructor); + var descriptor = new ServiceDescriptor(type, type, ServiceLifetime.Transient); + + var callSiteFactory = GetCallSiteFactory(descriptor); + + // Act and Assert + var ex = Assert.Throws( + () => callSiteFactory(type)); + Assert.Equal($"Unable to resolve service for type '{typeof(IFakeService)}' while attempting to activate '{type}'.", + ex.Message); + } + + [Theory] + [InlineData(typeof(TypeWithMultipleParameterizedConstructors))] + [InlineData(typeof(TypeWithSupersetConstructors))] + public void CreateCallSite_ThrowsIfTypeHasNoConstructurWithResolvableParameters(Type type) + { + // Arrange + var descriptor = new ServiceDescriptor(type, type, ServiceLifetime.Transient); + var callSiteFactory = GetCallSiteFactory( + descriptor, + new ServiceDescriptor(typeof(IFakeMultipleService), typeof(FakeService), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeScopedService), typeof(FakeService), ServiceLifetime.Transient) + ); + + // Act and Assert + var ex = Assert.Throws( + () => callSiteFactory(type)); + Assert.Equal($"No constructor for type '{type}' can be instantiated using services from the service container and default values.", + ex.Message); + } + + public static TheoryData CreateCallSite_ThrowsIfMultipleNonOverlappingConstructorsCanBeResolvedData => + new TheoryData, Type[][]> + { + { + typeof(TypeWithDefaultConstructorParameters), + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithDefaultConstructorParameters), typeof(TypeWithDefaultConstructorParameters), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFactoryService), typeof(FakeService), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeMultipleService), typeof(FakeService), ServiceLifetime.Transient) + ), + new[] + { + new[] { typeof(IFakeMultipleService), typeof(IFakeService) }, + new[] { typeof(IFactoryService), typeof(IFakeScopedService) } + } + }, + { + typeof(TypeWithMultipleParameterizedConstructors), + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithMultipleParameterizedConstructors), typeof(TypeWithMultipleParameterizedConstructors), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFactoryService), typeof(FakeService), ServiceLifetime.Transient) + ), + new[] + { + new[] { typeof(IFactoryService) }, + new[] { typeof(IFakeService) } + } + }, + { + typeof(TypeWithNonOverlappedConstructors), + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithNonOverlappedConstructors), typeof(TypeWithNonOverlappedConstructors), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeScopedService), typeof(FakeService), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeMultipleService), typeof(FakeService), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeOuterService), typeof(FakeService), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient) + ), + new[] + { + new[] { typeof(IFakeScopedService), typeof(IFakeService), typeof(IFakeMultipleService) }, + new[] { typeof(IFakeOuterService) } + } + }, + { + typeof(TypeWithUnresolvableEnumerableConstructors), + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithUnresolvableEnumerableConstructors), typeof(TypeWithUnresolvableEnumerableConstructors), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient) + ), + new[] + { + new[] { typeof(IFakeService) }, + new[] { typeof(IEnumerable) } + } + }, + { + typeof(TypeWithUnresolvableEnumerableConstructors), + GetCallSiteFactory( + new ServiceDescriptor(typeof(TypeWithUnresolvableEnumerableConstructors), typeof(TypeWithUnresolvableEnumerableConstructors), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFactoryService), typeof(FakeService), ServiceLifetime.Transient) + ), + new[] + { + new[] { typeof(IEnumerable) }, + new[] { typeof(IFactoryService) } + } + }, + }; + + [Theory] + [MemberData(nameof(CreateCallSite_ThrowsIfMultipleNonOverlappingConstructorsCanBeResolvedData))] + public void CreateCallSite_ThrowsIfMultipleNonOverlappingConstructorsCanBeResolved( + Type type, + Func callSiteFactory, + Type[][] expectedConstructorParameterTypes) + { + // Arrange + var expectedMessage = + string.Join( + Environment.NewLine, + $"Unable to activate type '{type}'. The following constructors are ambiguous:", + GetConstructor(type, expectedConstructorParameterTypes[0]), + GetConstructor(type, expectedConstructorParameterTypes[1])); + + // Act and Assert + var ex = Assert.Throws( + () => callSiteFactory(type)); + Assert.Equal(expectedMessage, ex.Message); + } + + [Fact] + public void CreateCallSite_ThrowsIfMultipleNonOverlappingConstructorsForGenericTypesCanBeResolved() + { + // Arrange + var type = typeof(TypeWithGenericServices); + var expectedMessage = $"Unable to activate type '{type}'. The following constructors are ambiguous:"; + + var callSiteFactory = GetCallSiteFactory( + new ServiceDescriptor(type, type, ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeMultipleService), typeof(FakeService), ServiceLifetime.Transient), + new ServiceDescriptor(typeof(IFakeOpenGenericService<>), typeof(FakeOpenGenericService<>), ServiceLifetime.Transient) + ); + + // Act and Assert + var ex = Assert.Throws( + () => callSiteFactory(type)); + Assert.StartsWith(expectedMessage, ex.Message); + } + + private static Func GetCallSiteFactory(params ServiceDescriptor[] descriptors) + { + var collection = new ServiceCollection(); + foreach (var descriptor in descriptors) + { + collection.Add(descriptor); + } + + var callSiteFactory = new CallSiteFactory(collection.ToArray()); + + return type => callSiteFactory.CreateCallSite(type, new CallSiteChain()); + } + + private static IEnumerable GetParameters(ConstructorCallSite constructorCallSite) => + constructorCallSite + .ConstructorInfo + .GetParameters() + .Select(p => p.ParameterType); + + private static ConstructorInfo GetConstructor(Type type, Type[] parameterTypes) => + type.GetTypeInfo().DeclaredConstructors.First( + c => Enumerable.SequenceEqual( + c.GetParameters().Select(p => p.ParameterType), + parameterTypes)); + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithDefaultConstructorParameters.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithDefaultConstructorParameters.cs new file mode 100644 index 00000000000..3f619365505 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithDefaultConstructorParameters.cs @@ -0,0 +1,27 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + public class TypeWithDefaultConstructorParameters + { + public TypeWithDefaultConstructorParameters( + IFakeMultipleService multipleService, + IFakeService fakeService = null) + { + } + + public TypeWithDefaultConstructorParameters( + IFactoryService factoryService) + { + } + + public TypeWithDefaultConstructorParameters( + IFactoryService factoryService, + IFakeScopedService singletonService = null) + { + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithEnumerableConstructors.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithEnumerableConstructors.cs new file mode 100644 index 00000000000..2a82ae5e9a7 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithEnumerableConstructors.cs @@ -0,0 +1,22 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Generic; +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + public class TypeWithEnumerableConstructors + { + public TypeWithEnumerableConstructors( + IEnumerable fakeServices) + { + } + + public TypeWithEnumerableConstructors( + IEnumerable fakeServices, + IEnumerable factoryServices) + { + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithGenericServices.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithGenericServices.cs new file mode 100644 index 00000000000..9cbee71f3ea --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithGenericServices.cs @@ -0,0 +1,29 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + public class TypeWithGenericServices + { + public TypeWithGenericServices( + IFakeService fakeService, + IFakeOpenGenericService logger) + { + } + + public TypeWithGenericServices( + IFakeMultipleService multipleService, + IFakeService fakeService) + { + } + + public TypeWithGenericServices( + IFakeService fakeService, + IFactoryService factoryService, + IFakeOpenGenericService logger) + { + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithMultipleParameterizedConstructors.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithMultipleParameterizedConstructors.cs new file mode 100644 index 00000000000..6616fecb9c4 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithMultipleParameterizedConstructors.cs @@ -0,0 +1,18 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + public class TypeWithMultipleParameterizedConstructors + { + public TypeWithMultipleParameterizedConstructors(IFactoryService factoryService) + { + } + + public TypeWithMultipleParameterizedConstructors(IFakeService fakeService) + { + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithNoConstructors.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithNoConstructors.cs new file mode 100644 index 00000000000..a9f6c4d33c2 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithNoConstructors.cs @@ -0,0 +1,9 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + public class TypeWithNoConstructors + { + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithNoPublicConstructors.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithNoPublicConstructors.cs new file mode 100644 index 00000000000..175d84a9d33 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithNoPublicConstructors.cs @@ -0,0 +1,16 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + public class TypeWithNoPublicConstructors + { + private TypeWithNoPublicConstructors() + { + } + + protected TypeWithNoPublicConstructors(string name) + { + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithNonOverlappedConstructors.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithNonOverlappedConstructors.cs new file mode 100644 index 00000000000..3887c672b5f --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithNonOverlappedConstructors.cs @@ -0,0 +1,28 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + public class TypeWithNonOverlappedConstructors + { + public TypeWithNonOverlappedConstructors( + IFakeOuterService outerService) + { + } + + public TypeWithNonOverlappedConstructors( + IFakeScopedService scopedService, + IFakeService fakeService) + { + } + + public TypeWithNonOverlappedConstructors( + IFakeScopedService scopedService, + IFakeService fakeService, + IFakeMultipleService multipleService) + { + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithParameterizedAndNullaryConstructor.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithParameterizedAndNullaryConstructor.cs new file mode 100644 index 00000000000..f52d1a69bb5 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithParameterizedAndNullaryConstructor.cs @@ -0,0 +1,20 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + public class TypeWithParameterizedAndNullaryConstructor + { + public TypeWithParameterizedAndNullaryConstructor() + : this(new FakeService()) + { + + } + + public TypeWithParameterizedAndNullaryConstructor(IFakeService fakeService) + { + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithParameterizedConstructor.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithParameterizedConstructor.cs new file mode 100644 index 00000000000..87ee987b2a6 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithParameterizedConstructor.cs @@ -0,0 +1,14 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + public class TypeWithParameterizedConstructor + { + public TypeWithParameterizedConstructor(IFakeService fakeService) + { + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithParameterlessConstructor.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithParameterlessConstructor.cs new file mode 100644 index 00000000000..1cb750db6b5 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithParameterlessConstructor.cs @@ -0,0 +1,12 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + public class TypeWithParameterlessConstructor + { + public TypeWithParameterlessConstructor() + { + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithParameterlessPublicConstructor.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithParameterlessPublicConstructor.cs new file mode 100644 index 00000000000..3a0158f00b9 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithParameterlessPublicConstructor.cs @@ -0,0 +1,17 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + public class TypeWithParameterlessPublicConstructor + { + public TypeWithParameterlessPublicConstructor() + : this("some name") + { + } + + protected TypeWithParameterlessPublicConstructor(string name) + { + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithUnresolvableEnumerableConstructors.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithUnresolvableEnumerableConstructors.cs new file mode 100644 index 00000000000..770653eb24b --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceLookup/Types/TypeWithUnresolvableEnumerableConstructors.cs @@ -0,0 +1,23 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Generic; +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + public class TypeWithUnresolvableEnumerableConstructors + { + public TypeWithUnresolvableEnumerableConstructors(IFakeService fakeService) + { + } + + public TypeWithUnresolvableEnumerableConstructors(IEnumerable fakeService) + { + } + + public TypeWithUnresolvableEnumerableConstructors(IFactoryService factoryService) + { + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderCompilationTest.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderCompilationTest.cs new file mode 100644 index 00000000000..17a63b51f63 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderCompilationTest.cs @@ -0,0 +1,58 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Threading; +using System.Threading.Tasks; +using Xunit; + +namespace Microsoft.Extensions.DependencyInjection.Tests +{ + public class ServiceProviderCompilationTest + { + [Theory] +#if DEBUG + [InlineData(ServiceProviderMode.Dynamic, typeof(I150))] + [InlineData(ServiceProviderMode.Runtime, typeof(I150))] + [InlineData(ServiceProviderMode.ILEmit, typeof(I150))] + [InlineData(ServiceProviderMode.Expressions, typeof(I150))] +#else + [InlineData(ServiceProviderMode.Dynamic, typeof(I200))] + [InlineData(ServiceProviderMode.Runtime, typeof(I200))] + [InlineData(ServiceProviderMode.ILEmit, typeof(I200))] + [InlineData(ServiceProviderMode.Expressions, typeof(I200))] +#endif + private async Task CompilesInLimitedStackSpace(ServiceProviderMode mode, Type serviceType) + { + // Arrange + var stackSize = 256 * 1024; + var serviceCollection = new ServiceCollection(); + CompilationTestDataProvider.Register(serviceCollection); + var serviceProvider = serviceCollection.BuildServiceProvider(new ServiceProviderOptions { Mode = mode }); + + // Act + Assert + + var tsc = new TaskCompletionSource(); + var thread = new Thread(() => + { + try + { + object service = null; + for (int i = 0; i < 10; i++) + { + service = serviceProvider.GetService(serviceType); + } + tsc.SetResult(service); + } + catch (Exception ex) + { + tsc.SetException(ex); + } + }, stackSize); + + thread.Start(); + thread.Join(); + await tsc.Task; + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderCompilationTestData.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderCompilationTestData.cs new file mode 100644 index 00000000000..9e5ecd85111 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderCompilationTestData.cs @@ -0,0 +1,3013 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.Extensions.DependencyInjection.Tests +{ + interface I0 { } + class S0 : I0 { } + interface I1 { } + class S1 : I1 { public S1(I0 s) { } } + interface I2 { } + class S2 : I2 { public S2(I1 s) { } } + interface I3 { } + class S3 : I3 { public S3(I2 s) { } } + interface I4 { } + class S4 : I4 { public S4(I3 s) { } } + interface I5 { } + class S5 : I5 { public S5(I4 s) { } } + interface I6 { } + class S6 : I6 { public S6(I5 s) { } } + interface I7 { } + class S7 : I7 { public S7(I6 s) { } } + interface I8 { } + class S8 : I8 { public S8(I7 s) { } } + interface I9 { } + class S9 : I9 { public S9(I8 s) { } } + interface I10 { } + class S10 : I10 { public S10(I9 s) { } } + interface I11 { } + class S11 : I11 { public S11(I10 s) { } } + interface I12 { } + class S12 : I12 { public S12(I11 s) { } } + interface I13 { } + class S13 : I13 { public S13(I12 s) { } } + interface I14 { } + class S14 : I14 { public S14(I13 s) { } } + interface I15 { } + class S15 : I15 { public S15(I14 s) { } } + interface I16 { } + class S16 : I16 { public S16(I15 s) { } } + interface I17 { } + class S17 : I17 { public S17(I16 s) { } } + interface I18 { } + class S18 : I18 { public S18(I17 s) { } } + interface I19 { } + class S19 : I19 { public S19(I18 s) { } } + interface I20 { } + class S20 : I20 { public S20(I19 s) { } } + interface I21 { } + class S21 : I21 { public S21(I20 s) { } } + interface I22 { } + class S22 : I22 { public S22(I21 s) { } } + interface I23 { } + class S23 : I23 { public S23(I22 s) { } } + interface I24 { } + class S24 : I24 { public S24(I23 s) { } } + interface I25 { } + class S25 : I25 { public S25(I24 s) { } } + interface I26 { } + class S26 : I26 { public S26(I25 s) { } } + interface I27 { } + class S27 : I27 { public S27(I26 s) { } } + interface I28 { } + class S28 : I28 { public S28(I27 s) { } } + interface I29 { } + class S29 : I29 { public S29(I28 s) { } } + interface I30 { } + class S30 : I30 { public S30(I29 s) { } } + interface I31 { } + class S31 : I31 { public S31(I30 s) { } } + interface I32 { } + class S32 : I32 { public S32(I31 s) { } } + interface I33 { } + class S33 : I33 { public S33(I32 s) { } } + interface I34 { } + class S34 : I34 { public S34(I33 s) { } } + interface I35 { } + class S35 : I35 { public S35(I34 s) { } } + interface I36 { } + class S36 : I36 { public S36(I35 s) { } } + interface I37 { } + class S37 : I37 { public S37(I36 s) { } } + interface I38 { } + class S38 : I38 { public S38(I37 s) { } } + interface I39 { } + class S39 : I39 { public S39(I38 s) { } } + interface I40 { } + class S40 : I40 { public S40(I39 s) { } } + interface I41 { } + class S41 : I41 { public S41(I40 s) { } } + interface I42 { } + class S42 : I42 { public S42(I41 s) { } } + interface I43 { } + class S43 : I43 { public S43(I42 s) { } } + interface I44 { } + class S44 : I44 { public S44(I43 s) { } } + interface I45 { } + class S45 : I45 { public S45(I44 s) { } } + interface I46 { } + class S46 : I46 { public S46(I45 s) { } } + interface I47 { } + class S47 : I47 { public S47(I46 s) { } } + interface I48 { } + class S48 : I48 { public S48(I47 s) { } } + interface I49 { } + class S49 : I49 { public S49(I48 s) { } } + interface I50 { } + class S50 : I50 { public S50(I49 s) { } } + interface I51 { } + class S51 : I51 { public S51(I50 s) { } } + interface I52 { } + class S52 : I52 { public S52(I51 s) { } } + interface I53 { } + class S53 : I53 { public S53(I52 s) { } } + interface I54 { } + class S54 : I54 { public S54(I53 s) { } } + interface I55 { } + class S55 : I55 { public S55(I54 s) { } } + interface I56 { } + class S56 : I56 { public S56(I55 s) { } } + interface I57 { } + class S57 : I57 { public S57(I56 s) { } } + interface I58 { } + class S58 : I58 { public S58(I57 s) { } } + interface I59 { } + class S59 : I59 { public S59(I58 s) { } } + interface I60 { } + class S60 : I60 { public S60(I59 s) { } } + interface I61 { } + class S61 : I61 { public S61(I60 s) { } } + interface I62 { } + class S62 : I62 { public S62(I61 s) { } } + interface I63 { } + class S63 : I63 { public S63(I62 s) { } } + interface I64 { } + class S64 : I64 { public S64(I63 s) { } } + interface I65 { } + class S65 : I65 { public S65(I64 s) { } } + interface I66 { } + class S66 : I66 { public S66(I65 s) { } } + interface I67 { } + class S67 : I67 { public S67(I66 s) { } } + interface I68 { } + class S68 : I68 { public S68(I67 s) { } } + interface I69 { } + class S69 : I69 { public S69(I68 s) { } } + interface I70 { } + class S70 : I70 { public S70(I69 s) { } } + interface I71 { } + class S71 : I71 { public S71(I70 s) { } } + interface I72 { } + class S72 : I72 { public S72(I71 s) { } } + interface I73 { } + class S73 : I73 { public S73(I72 s) { } } + interface I74 { } + class S74 : I74 { public S74(I73 s) { } } + interface I75 { } + class S75 : I75 { public S75(I74 s) { } } + interface I76 { } + class S76 : I76 { public S76(I75 s) { } } + interface I77 { } + class S77 : I77 { public S77(I76 s) { } } + interface I78 { } + class S78 : I78 { public S78(I77 s) { } } + interface I79 { } + class S79 : I79 { public S79(I78 s) { } } + interface I80 { } + class S80 : I80 { public S80(I79 s) { } } + interface I81 { } + class S81 : I81 { public S81(I80 s) { } } + interface I82 { } + class S82 : I82 { public S82(I81 s) { } } + interface I83 { } + class S83 : I83 { public S83(I82 s) { } } + interface I84 { } + class S84 : I84 { public S84(I83 s) { } } + interface I85 { } + class S85 : I85 { public S85(I84 s) { } } + interface I86 { } + class S86 : I86 { public S86(I85 s) { } } + interface I87 { } + class S87 : I87 { public S87(I86 s) { } } + interface I88 { } + class S88 : I88 { public S88(I87 s) { } } + interface I89 { } + class S89 : I89 { public S89(I88 s) { } } + interface I90 { } + class S90 : I90 { public S90(I89 s) { } } + interface I91 { } + class S91 : I91 { public S91(I90 s) { } } + interface I92 { } + class S92 : I92 { public S92(I91 s) { } } + interface I93 { } + class S93 : I93 { public S93(I92 s) { } } + interface I94 { } + class S94 : I94 { public S94(I93 s) { } } + interface I95 { } + class S95 : I95 { public S95(I94 s) { } } + interface I96 { } + class S96 : I96 { public S96(I95 s) { } } + interface I97 { } + class S97 : I97 { public S97(I96 s) { } } + interface I98 { } + class S98 : I98 { public S98(I97 s) { } } + interface I99 { } + class S99 : I99 { public S99(I98 s) { } } + interface I100 { } + class S100 : I100 { public S100(I99 s) { } } + interface I101 { } + class S101 : I101 { public S101(I100 s) { } } + interface I102 { } + class S102 : I102 { public S102(I101 s) { } } + interface I103 { } + class S103 : I103 { public S103(I102 s) { } } + interface I104 { } + class S104 : I104 { public S104(I103 s) { } } + interface I105 { } + class S105 : I105 { public S105(I104 s) { } } + interface I106 { } + class S106 : I106 { public S106(I105 s) { } } + interface I107 { } + class S107 : I107 { public S107(I106 s) { } } + interface I108 { } + class S108 : I108 { public S108(I107 s) { } } + interface I109 { } + class S109 : I109 { public S109(I108 s) { } } + interface I110 { } + class S110 : I110 { public S110(I109 s) { } } + interface I111 { } + class S111 : I111 { public S111(I110 s) { } } + interface I112 { } + class S112 : I112 { public S112(I111 s) { } } + interface I113 { } + class S113 : I113 { public S113(I112 s) { } } + interface I114 { } + class S114 : I114 { public S114(I113 s) { } } + interface I115 { } + class S115 : I115 { public S115(I114 s) { } } + interface I116 { } + class S116 : I116 { public S116(I115 s) { } } + interface I117 { } + class S117 : I117 { public S117(I116 s) { } } + interface I118 { } + class S118 : I118 { public S118(I117 s) { } } + interface I119 { } + class S119 : I119 { public S119(I118 s) { } } + interface I120 { } + class S120 : I120 { public S120(I119 s) { } } + interface I121 { } + class S121 : I121 { public S121(I120 s) { } } + interface I122 { } + class S122 : I122 { public S122(I121 s) { } } + interface I123 { } + class S123 : I123 { public S123(I122 s) { } } + interface I124 { } + class S124 : I124 { public S124(I123 s) { } } + interface I125 { } + class S125 : I125 { public S125(I124 s) { } } + interface I126 { } + class S126 : I126 { public S126(I125 s) { } } + interface I127 { } + class S127 : I127 { public S127(I126 s) { } } + interface I128 { } + class S128 : I128 { public S128(I127 s) { } } + interface I129 { } + class S129 : I129 { public S129(I128 s) { } } + interface I130 { } + class S130 : I130 { public S130(I129 s) { } } + interface I131 { } + class S131 : I131 { public S131(I130 s) { } } + interface I132 { } + class S132 : I132 { public S132(I131 s) { } } + interface I133 { } + class S133 : I133 { public S133(I132 s) { } } + interface I134 { } + class S134 : I134 { public S134(I133 s) { } } + interface I135 { } + class S135 : I135 { public S135(I134 s) { } } + interface I136 { } + class S136 : I136 { public S136(I135 s) { } } + interface I137 { } + class S137 : I137 { public S137(I136 s) { } } + interface I138 { } + class S138 : I138 { public S138(I137 s) { } } + interface I139 { } + class S139 : I139 { public S139(I138 s) { } } + interface I140 { } + class S140 : I140 { public S140(I139 s) { } } + interface I141 { } + class S141 : I141 { public S141(I140 s) { } } + interface I142 { } + class S142 : I142 { public S142(I141 s) { } } + interface I143 { } + class S143 : I143 { public S143(I142 s) { } } + interface I144 { } + class S144 : I144 { public S144(I143 s) { } } + interface I145 { } + class S145 : I145 { public S145(I144 s) { } } + interface I146 { } + class S146 : I146 { public S146(I145 s) { } } + interface I147 { } + class S147 : I147 { public S147(I146 s) { } } + interface I148 { } + class S148 : I148 { public S148(I147 s) { } } + interface I149 { } + class S149 : I149 { public S149(I148 s) { } } + interface I150 { } + class S150 : I150 { public S150(I149 s) { } } + interface I151 { } + class S151 : I151 { public S151(I150 s) { } } + interface I152 { } + class S152 : I152 { public S152(I151 s) { } } + interface I153 { } + class S153 : I153 { public S153(I152 s) { } } + interface I154 { } + class S154 : I154 { public S154(I153 s) { } } + interface I155 { } + class S155 : I155 { public S155(I154 s) { } } + interface I156 { } + class S156 : I156 { public S156(I155 s) { } } + interface I157 { } + class S157 : I157 { public S157(I156 s) { } } + interface I158 { } + class S158 : I158 { public S158(I157 s) { } } + interface I159 { } + class S159 : I159 { public S159(I158 s) { } } + interface I160 { } + class S160 : I160 { public S160(I159 s) { } } + interface I161 { } + class S161 : I161 { public S161(I160 s) { } } + interface I162 { } + class S162 : I162 { public S162(I161 s) { } } + interface I163 { } + class S163 : I163 { public S163(I162 s) { } } + interface I164 { } + class S164 : I164 { public S164(I163 s) { } } + interface I165 { } + class S165 : I165 { public S165(I164 s) { } } + interface I166 { } + class S166 : I166 { public S166(I165 s) { } } + interface I167 { } + class S167 : I167 { public S167(I166 s) { } } + interface I168 { } + class S168 : I168 { public S168(I167 s) { } } + interface I169 { } + class S169 : I169 { public S169(I168 s) { } } + interface I170 { } + class S170 : I170 { public S170(I169 s) { } } + interface I171 { } + class S171 : I171 { public S171(I170 s) { } } + interface I172 { } + class S172 : I172 { public S172(I171 s) { } } + interface I173 { } + class S173 : I173 { public S173(I172 s) { } } + interface I174 { } + class S174 : I174 { public S174(I173 s) { } } + interface I175 { } + class S175 : I175 { public S175(I174 s) { } } + interface I176 { } + class S176 : I176 { public S176(I175 s) { } } + interface I177 { } + class S177 : I177 { public S177(I176 s) { } } + interface I178 { } + class S178 : I178 { public S178(I177 s) { } } + interface I179 { } + class S179 : I179 { public S179(I178 s) { } } + interface I180 { } + class S180 : I180 { public S180(I179 s) { } } + interface I181 { } + class S181 : I181 { public S181(I180 s) { } } + interface I182 { } + class S182 : I182 { public S182(I181 s) { } } + interface I183 { } + class S183 : I183 { public S183(I182 s) { } } + interface I184 { } + class S184 : I184 { public S184(I183 s) { } } + interface I185 { } + class S185 : I185 { public S185(I184 s) { } } + interface I186 { } + class S186 : I186 { public S186(I185 s) { } } + interface I187 { } + class S187 : I187 { public S187(I186 s) { } } + interface I188 { } + class S188 : I188 { public S188(I187 s) { } } + interface I189 { } + class S189 : I189 { public S189(I188 s) { } } + interface I190 { } + class S190 : I190 { public S190(I189 s) { } } + interface I191 { } + class S191 : I191 { public S191(I190 s) { } } + interface I192 { } + class S192 : I192 { public S192(I191 s) { } } + interface I193 { } + class S193 : I193 { public S193(I192 s) { } } + interface I194 { } + class S194 : I194 { public S194(I193 s) { } } + interface I195 { } + class S195 : I195 { public S195(I194 s) { } } + interface I196 { } + class S196 : I196 { public S196(I195 s) { } } + interface I197 { } + class S197 : I197 { public S197(I196 s) { } } + interface I198 { } + class S198 : I198 { public S198(I197 s) { } } + interface I199 { } + class S199 : I199 { public S199(I198 s) { } } + interface I200 { } + class S200 : I200 { public S200(I199 s) { } } + interface I201 { } + class S201 : I201 { public S201(I200 s) { } } + interface I202 { } + class S202 : I202 { public S202(I201 s) { } } + interface I203 { } + class S203 : I203 { public S203(I202 s) { } } + interface I204 { } + class S204 : I204 { public S204(I203 s) { } } + interface I205 { } + class S205 : I205 { public S205(I204 s) { } } + interface I206 { } + class S206 : I206 { public S206(I205 s) { } } + interface I207 { } + class S207 : I207 { public S207(I206 s) { } } + interface I208 { } + class S208 : I208 { public S208(I207 s) { } } + interface I209 { } + class S209 : I209 { public S209(I208 s) { } } + interface I210 { } + class S210 : I210 { public S210(I209 s) { } } + interface I211 { } + class S211 : I211 { public S211(I210 s) { } } + interface I212 { } + class S212 : I212 { public S212(I211 s) { } } + interface I213 { } + class S213 : I213 { public S213(I212 s) { } } + interface I214 { } + class S214 : I214 { public S214(I213 s) { } } + interface I215 { } + class S215 : I215 { public S215(I214 s) { } } + interface I216 { } + class S216 : I216 { public S216(I215 s) { } } + interface I217 { } + class S217 : I217 { public S217(I216 s) { } } + interface I218 { } + class S218 : I218 { public S218(I217 s) { } } + interface I219 { } + class S219 : I219 { public S219(I218 s) { } } + interface I220 { } + class S220 : I220 { public S220(I219 s) { } } + interface I221 { } + class S221 : I221 { public S221(I220 s) { } } + interface I222 { } + class S222 : I222 { public S222(I221 s) { } } + interface I223 { } + class S223 : I223 { public S223(I222 s) { } } + interface I224 { } + class S224 : I224 { public S224(I223 s) { } } + interface I225 { } + class S225 : I225 { public S225(I224 s) { } } + interface I226 { } + class S226 : I226 { public S226(I225 s) { } } + interface I227 { } + class S227 : I227 { public S227(I226 s) { } } + interface I228 { } + class S228 : I228 { public S228(I227 s) { } } + interface I229 { } + class S229 : I229 { public S229(I228 s) { } } + interface I230 { } + class S230 : I230 { public S230(I229 s) { } } + interface I231 { } + class S231 : I231 { public S231(I230 s) { } } + interface I232 { } + class S232 : I232 { public S232(I231 s) { } } + interface I233 { } + class S233 : I233 { public S233(I232 s) { } } + interface I234 { } + class S234 : I234 { public S234(I233 s) { } } + interface I235 { } + class S235 : I235 { public S235(I234 s) { } } + interface I236 { } + class S236 : I236 { public S236(I235 s) { } } + interface I237 { } + class S237 : I237 { public S237(I236 s) { } } + interface I238 { } + class S238 : I238 { public S238(I237 s) { } } + interface I239 { } + class S239 : I239 { public S239(I238 s) { } } + interface I240 { } + class S240 : I240 { public S240(I239 s) { } } + interface I241 { } + class S241 : I241 { public S241(I240 s) { } } + interface I242 { } + class S242 : I242 { public S242(I241 s) { } } + interface I243 { } + class S243 : I243 { public S243(I242 s) { } } + interface I244 { } + class S244 : I244 { public S244(I243 s) { } } + interface I245 { } + class S245 : I245 { public S245(I244 s) { } } + interface I246 { } + class S246 : I246 { public S246(I245 s) { } } + interface I247 { } + class S247 : I247 { public S247(I246 s) { } } + interface I248 { } + class S248 : I248 { public S248(I247 s) { } } + interface I249 { } + class S249 : I249 { public S249(I248 s) { } } + interface I250 { } + class S250 : I250 { public S250(I249 s) { } } + interface I251 { } + class S251 : I251 { public S251(I250 s) { } } + interface I252 { } + class S252 : I252 { public S252(I251 s) { } } + interface I253 { } + class S253 : I253 { public S253(I252 s) { } } + interface I254 { } + class S254 : I254 { public S254(I253 s) { } } + interface I255 { } + class S255 : I255 { public S255(I254 s) { } } + interface I256 { } + class S256 : I256 { public S256(I255 s) { } } + interface I257 { } + class S257 : I257 { public S257(I256 s) { } } + interface I258 { } + class S258 : I258 { public S258(I257 s) { } } + interface I259 { } + class S259 : I259 { public S259(I258 s) { } } + interface I260 { } + class S260 : I260 { public S260(I259 s) { } } + interface I261 { } + class S261 : I261 { public S261(I260 s) { } } + interface I262 { } + class S262 : I262 { public S262(I261 s) { } } + interface I263 { } + class S263 : I263 { public S263(I262 s) { } } + interface I264 { } + class S264 : I264 { public S264(I263 s) { } } + interface I265 { } + class S265 : I265 { public S265(I264 s) { } } + interface I266 { } + class S266 : I266 { public S266(I265 s) { } } + interface I267 { } + class S267 : I267 { public S267(I266 s) { } } + interface I268 { } + class S268 : I268 { public S268(I267 s) { } } + interface I269 { } + class S269 : I269 { public S269(I268 s) { } } + interface I270 { } + class S270 : I270 { public S270(I269 s) { } } + interface I271 { } + class S271 : I271 { public S271(I270 s) { } } + interface I272 { } + class S272 : I272 { public S272(I271 s) { } } + interface I273 { } + class S273 : I273 { public S273(I272 s) { } } + interface I274 { } + class S274 : I274 { public S274(I273 s) { } } + interface I275 { } + class S275 : I275 { public S275(I274 s) { } } + interface I276 { } + class S276 : I276 { public S276(I275 s) { } } + interface I277 { } + class S277 : I277 { public S277(I276 s) { } } + interface I278 { } + class S278 : I278 { public S278(I277 s) { } } + interface I279 { } + class S279 : I279 { public S279(I278 s) { } } + interface I280 { } + class S280 : I280 { public S280(I279 s) { } } + interface I281 { } + class S281 : I281 { public S281(I280 s) { } } + interface I282 { } + class S282 : I282 { public S282(I281 s) { } } + interface I283 { } + class S283 : I283 { public S283(I282 s) { } } + interface I284 { } + class S284 : I284 { public S284(I283 s) { } } + interface I285 { } + class S285 : I285 { public S285(I284 s) { } } + interface I286 { } + class S286 : I286 { public S286(I285 s) { } } + interface I287 { } + class S287 : I287 { public S287(I286 s) { } } + interface I288 { } + class S288 : I288 { public S288(I287 s) { } } + interface I289 { } + class S289 : I289 { public S289(I288 s) { } } + interface I290 { } + class S290 : I290 { public S290(I289 s) { } } + interface I291 { } + class S291 : I291 { public S291(I290 s) { } } + interface I292 { } + class S292 : I292 { public S292(I291 s) { } } + interface I293 { } + class S293 : I293 { public S293(I292 s) { } } + interface I294 { } + class S294 : I294 { public S294(I293 s) { } } + interface I295 { } + class S295 : I295 { public S295(I294 s) { } } + interface I296 { } + class S296 : I296 { public S296(I295 s) { } } + interface I297 { } + class S297 : I297 { public S297(I296 s) { } } + interface I298 { } + class S298 : I298 { public S298(I297 s) { } } + interface I299 { } + class S299 : I299 { public S299(I298 s) { } } + interface I300 { } + class S300 : I300 { public S300(I299 s) { } } + interface I301 { } + class S301 : I301 { public S301(I300 s) { } } + interface I302 { } + class S302 : I302 { public S302(I301 s) { } } + interface I303 { } + class S303 : I303 { public S303(I302 s) { } } + interface I304 { } + class S304 : I304 { public S304(I303 s) { } } + interface I305 { } + class S305 : I305 { public S305(I304 s) { } } + interface I306 { } + class S306 : I306 { public S306(I305 s) { } } + interface I307 { } + class S307 : I307 { public S307(I306 s) { } } + interface I308 { } + class S308 : I308 { public S308(I307 s) { } } + interface I309 { } + class S309 : I309 { public S309(I308 s) { } } + interface I310 { } + class S310 : I310 { public S310(I309 s) { } } + interface I311 { } + class S311 : I311 { public S311(I310 s) { } } + interface I312 { } + class S312 : I312 { public S312(I311 s) { } } + interface I313 { } + class S313 : I313 { public S313(I312 s) { } } + interface I314 { } + class S314 : I314 { public S314(I313 s) { } } + interface I315 { } + class S315 : I315 { public S315(I314 s) { } } + interface I316 { } + class S316 : I316 { public S316(I315 s) { } } + interface I317 { } + class S317 : I317 { public S317(I316 s) { } } + interface I318 { } + class S318 : I318 { public S318(I317 s) { } } + interface I319 { } + class S319 : I319 { public S319(I318 s) { } } + interface I320 { } + class S320 : I320 { public S320(I319 s) { } } + interface I321 { } + class S321 : I321 { public S321(I320 s) { } } + interface I322 { } + class S322 : I322 { public S322(I321 s) { } } + interface I323 { } + class S323 : I323 { public S323(I322 s) { } } + interface I324 { } + class S324 : I324 { public S324(I323 s) { } } + interface I325 { } + class S325 : I325 { public S325(I324 s) { } } + interface I326 { } + class S326 : I326 { public S326(I325 s) { } } + interface I327 { } + class S327 : I327 { public S327(I326 s) { } } + interface I328 { } + class S328 : I328 { public S328(I327 s) { } } + interface I329 { } + class S329 : I329 { public S329(I328 s) { } } + interface I330 { } + class S330 : I330 { public S330(I329 s) { } } + interface I331 { } + class S331 : I331 { public S331(I330 s) { } } + interface I332 { } + class S332 : I332 { public S332(I331 s) { } } + interface I333 { } + class S333 : I333 { public S333(I332 s) { } } + interface I334 { } + class S334 : I334 { public S334(I333 s) { } } + interface I335 { } + class S335 : I335 { public S335(I334 s) { } } + interface I336 { } + class S336 : I336 { public S336(I335 s) { } } + interface I337 { } + class S337 : I337 { public S337(I336 s) { } } + interface I338 { } + class S338 : I338 { public S338(I337 s) { } } + interface I339 { } + class S339 : I339 { public S339(I338 s) { } } + interface I340 { } + class S340 : I340 { public S340(I339 s) { } } + interface I341 { } + class S341 : I341 { public S341(I340 s) { } } + interface I342 { } + class S342 : I342 { public S342(I341 s) { } } + interface I343 { } + class S343 : I343 { public S343(I342 s) { } } + interface I344 { } + class S344 : I344 { public S344(I343 s) { } } + interface I345 { } + class S345 : I345 { public S345(I344 s) { } } + interface I346 { } + class S346 : I346 { public S346(I345 s) { } } + interface I347 { } + class S347 : I347 { public S347(I346 s) { } } + interface I348 { } + class S348 : I348 { public S348(I347 s) { } } + interface I349 { } + class S349 : I349 { public S349(I348 s) { } } + interface I350 { } + class S350 : I350 { public S350(I349 s) { } } + interface I351 { } + class S351 : I351 { public S351(I350 s) { } } + interface I352 { } + class S352 : I352 { public S352(I351 s) { } } + interface I353 { } + class S353 : I353 { public S353(I352 s) { } } + interface I354 { } + class S354 : I354 { public S354(I353 s) { } } + interface I355 { } + class S355 : I355 { public S355(I354 s) { } } + interface I356 { } + class S356 : I356 { public S356(I355 s) { } } + interface I357 { } + class S357 : I357 { public S357(I356 s) { } } + interface I358 { } + class S358 : I358 { public S358(I357 s) { } } + interface I359 { } + class S359 : I359 { public S359(I358 s) { } } + interface I360 { } + class S360 : I360 { public S360(I359 s) { } } + interface I361 { } + class S361 : I361 { public S361(I360 s) { } } + interface I362 { } + class S362 : I362 { public S362(I361 s) { } } + interface I363 { } + class S363 : I363 { public S363(I362 s) { } } + interface I364 { } + class S364 : I364 { public S364(I363 s) { } } + interface I365 { } + class S365 : I365 { public S365(I364 s) { } } + interface I366 { } + class S366 : I366 { public S366(I365 s) { } } + interface I367 { } + class S367 : I367 { public S367(I366 s) { } } + interface I368 { } + class S368 : I368 { public S368(I367 s) { } } + interface I369 { } + class S369 : I369 { public S369(I368 s) { } } + interface I370 { } + class S370 : I370 { public S370(I369 s) { } } + interface I371 { } + class S371 : I371 { public S371(I370 s) { } } + interface I372 { } + class S372 : I372 { public S372(I371 s) { } } + interface I373 { } + class S373 : I373 { public S373(I372 s) { } } + interface I374 { } + class S374 : I374 { public S374(I373 s) { } } + interface I375 { } + class S375 : I375 { public S375(I374 s) { } } + interface I376 { } + class S376 : I376 { public S376(I375 s) { } } + interface I377 { } + class S377 : I377 { public S377(I376 s) { } } + interface I378 { } + class S378 : I378 { public S378(I377 s) { } } + interface I379 { } + class S379 : I379 { public S379(I378 s) { } } + interface I380 { } + class S380 : I380 { public S380(I379 s) { } } + interface I381 { } + class S381 : I381 { public S381(I380 s) { } } + interface I382 { } + class S382 : I382 { public S382(I381 s) { } } + interface I383 { } + class S383 : I383 { public S383(I382 s) { } } + interface I384 { } + class S384 : I384 { public S384(I383 s) { } } + interface I385 { } + class S385 : I385 { public S385(I384 s) { } } + interface I386 { } + class S386 : I386 { public S386(I385 s) { } } + interface I387 { } + class S387 : I387 { public S387(I386 s) { } } + interface I388 { } + class S388 : I388 { public S388(I387 s) { } } + interface I389 { } + class S389 : I389 { public S389(I388 s) { } } + interface I390 { } + class S390 : I390 { public S390(I389 s) { } } + interface I391 { } + class S391 : I391 { public S391(I390 s) { } } + interface I392 { } + class S392 : I392 { public S392(I391 s) { } } + interface I393 { } + class S393 : I393 { public S393(I392 s) { } } + interface I394 { } + class S394 : I394 { public S394(I393 s) { } } + interface I395 { } + class S395 : I395 { public S395(I394 s) { } } + interface I396 { } + class S396 : I396 { public S396(I395 s) { } } + interface I397 { } + class S397 : I397 { public S397(I396 s) { } } + interface I398 { } + class S398 : I398 { public S398(I397 s) { } } + interface I399 { } + class S399 : I399 { public S399(I398 s) { } } + interface I400 { } + class S400 : I400 { public S400(I399 s) { } } + interface I401 { } + class S401 : I401 { public S401(I400 s) { } } + interface I402 { } + class S402 : I402 { public S402(I401 s) { } } + interface I403 { } + class S403 : I403 { public S403(I402 s) { } } + interface I404 { } + class S404 : I404 { public S404(I403 s) { } } + interface I405 { } + class S405 : I405 { public S405(I404 s) { } } + interface I406 { } + class S406 : I406 { public S406(I405 s) { } } + interface I407 { } + class S407 : I407 { public S407(I406 s) { } } + interface I408 { } + class S408 : I408 { public S408(I407 s) { } } + interface I409 { } + class S409 : I409 { public S409(I408 s) { } } + interface I410 { } + class S410 : I410 { public S410(I409 s) { } } + interface I411 { } + class S411 : I411 { public S411(I410 s) { } } + interface I412 { } + class S412 : I412 { public S412(I411 s) { } } + interface I413 { } + class S413 : I413 { public S413(I412 s) { } } + interface I414 { } + class S414 : I414 { public S414(I413 s) { } } + interface I415 { } + class S415 : I415 { public S415(I414 s) { } } + interface I416 { } + class S416 : I416 { public S416(I415 s) { } } + interface I417 { } + class S417 : I417 { public S417(I416 s) { } } + interface I418 { } + class S418 : I418 { public S418(I417 s) { } } + interface I419 { } + class S419 : I419 { public S419(I418 s) { } } + interface I420 { } + class S420 : I420 { public S420(I419 s) { } } + interface I421 { } + class S421 : I421 { public S421(I420 s) { } } + interface I422 { } + class S422 : I422 { public S422(I421 s) { } } + interface I423 { } + class S423 : I423 { public S423(I422 s) { } } + interface I424 { } + class S424 : I424 { public S424(I423 s) { } } + interface I425 { } + class S425 : I425 { public S425(I424 s) { } } + interface I426 { } + class S426 : I426 { public S426(I425 s) { } } + interface I427 { } + class S427 : I427 { public S427(I426 s) { } } + interface I428 { } + class S428 : I428 { public S428(I427 s) { } } + interface I429 { } + class S429 : I429 { public S429(I428 s) { } } + interface I430 { } + class S430 : I430 { public S430(I429 s) { } } + interface I431 { } + class S431 : I431 { public S431(I430 s) { } } + interface I432 { } + class S432 : I432 { public S432(I431 s) { } } + interface I433 { } + class S433 : I433 { public S433(I432 s) { } } + interface I434 { } + class S434 : I434 { public S434(I433 s) { } } + interface I435 { } + class S435 : I435 { public S435(I434 s) { } } + interface I436 { } + class S436 : I436 { public S436(I435 s) { } } + interface I437 { } + class S437 : I437 { public S437(I436 s) { } } + interface I438 { } + class S438 : I438 { public S438(I437 s) { } } + interface I439 { } + class S439 : I439 { public S439(I438 s) { } } + interface I440 { } + class S440 : I440 { public S440(I439 s) { } } + interface I441 { } + class S441 : I441 { public S441(I440 s) { } } + interface I442 { } + class S442 : I442 { public S442(I441 s) { } } + interface I443 { } + class S443 : I443 { public S443(I442 s) { } } + interface I444 { } + class S444 : I444 { public S444(I443 s) { } } + interface I445 { } + class S445 : I445 { public S445(I444 s) { } } + interface I446 { } + class S446 : I446 { public S446(I445 s) { } } + interface I447 { } + class S447 : I447 { public S447(I446 s) { } } + interface I448 { } + class S448 : I448 { public S448(I447 s) { } } + interface I449 { } + class S449 : I449 { public S449(I448 s) { } } + interface I450 { } + class S450 : I450 { public S450(I449 s) { } } + interface I451 { } + class S451 : I451 { public S451(I450 s) { } } + interface I452 { } + class S452 : I452 { public S452(I451 s) { } } + interface I453 { } + class S453 : I453 { public S453(I452 s) { } } + interface I454 { } + class S454 : I454 { public S454(I453 s) { } } + interface I455 { } + class S455 : I455 { public S455(I454 s) { } } + interface I456 { } + class S456 : I456 { public S456(I455 s) { } } + interface I457 { } + class S457 : I457 { public S457(I456 s) { } } + interface I458 { } + class S458 : I458 { public S458(I457 s) { } } + interface I459 { } + class S459 : I459 { public S459(I458 s) { } } + interface I460 { } + class S460 : I460 { public S460(I459 s) { } } + interface I461 { } + class S461 : I461 { public S461(I460 s) { } } + interface I462 { } + class S462 : I462 { public S462(I461 s) { } } + interface I463 { } + class S463 : I463 { public S463(I462 s) { } } + interface I464 { } + class S464 : I464 { public S464(I463 s) { } } + interface I465 { } + class S465 : I465 { public S465(I464 s) { } } + interface I466 { } + class S466 : I466 { public S466(I465 s) { } } + interface I467 { } + class S467 : I467 { public S467(I466 s) { } } + interface I468 { } + class S468 : I468 { public S468(I467 s) { } } + interface I469 { } + class S469 : I469 { public S469(I468 s) { } } + interface I470 { } + class S470 : I470 { public S470(I469 s) { } } + interface I471 { } + class S471 : I471 { public S471(I470 s) { } } + interface I472 { } + class S472 : I472 { public S472(I471 s) { } } + interface I473 { } + class S473 : I473 { public S473(I472 s) { } } + interface I474 { } + class S474 : I474 { public S474(I473 s) { } } + interface I475 { } + class S475 : I475 { public S475(I474 s) { } } + interface I476 { } + class S476 : I476 { public S476(I475 s) { } } + interface I477 { } + class S477 : I477 { public S477(I476 s) { } } + interface I478 { } + class S478 : I478 { public S478(I477 s) { } } + interface I479 { } + class S479 : I479 { public S479(I478 s) { } } + interface I480 { } + class S480 : I480 { public S480(I479 s) { } } + interface I481 { } + class S481 : I481 { public S481(I480 s) { } } + interface I482 { } + class S482 : I482 { public S482(I481 s) { } } + interface I483 { } + class S483 : I483 { public S483(I482 s) { } } + interface I484 { } + class S484 : I484 { public S484(I483 s) { } } + interface I485 { } + class S485 : I485 { public S485(I484 s) { } } + interface I486 { } + class S486 : I486 { public S486(I485 s) { } } + interface I487 { } + class S487 : I487 { public S487(I486 s) { } } + interface I488 { } + class S488 : I488 { public S488(I487 s) { } } + interface I489 { } + class S489 : I489 { public S489(I488 s) { } } + interface I490 { } + class S490 : I490 { public S490(I489 s) { } } + interface I491 { } + class S491 : I491 { public S491(I490 s) { } } + interface I492 { } + class S492 : I492 { public S492(I491 s) { } } + interface I493 { } + class S493 : I493 { public S493(I492 s) { } } + interface I494 { } + class S494 : I494 { public S494(I493 s) { } } + interface I495 { } + class S495 : I495 { public S495(I494 s) { } } + interface I496 { } + class S496 : I496 { public S496(I495 s) { } } + interface I497 { } + class S497 : I497 { public S497(I496 s) { } } + interface I498 { } + class S498 : I498 { public S498(I497 s) { } } + interface I499 { } + class S499 : I499 { public S499(I498 s) { } } + interface I500 { } + class S500 : I500 { public S500(I499 s) { } } + interface I501 { } + class S501 : I501 { public S501(I500 s) { } } + interface I502 { } + class S502 : I502 { public S502(I501 s) { } } + interface I503 { } + class S503 : I503 { public S503(I502 s) { } } + interface I504 { } + class S504 : I504 { public S504(I503 s) { } } + interface I505 { } + class S505 : I505 { public S505(I504 s) { } } + interface I506 { } + class S506 : I506 { public S506(I505 s) { } } + interface I507 { } + class S507 : I507 { public S507(I506 s) { } } + interface I508 { } + class S508 : I508 { public S508(I507 s) { } } + interface I509 { } + class S509 : I509 { public S509(I508 s) { } } + interface I510 { } + class S510 : I510 { public S510(I509 s) { } } + interface I511 { } + class S511 : I511 { public S511(I510 s) { } } + interface I512 { } + class S512 : I512 { public S512(I511 s) { } } + interface I513 { } + class S513 : I513 { public S513(I512 s) { } } + interface I514 { } + class S514 : I514 { public S514(I513 s) { } } + interface I515 { } + class S515 : I515 { public S515(I514 s) { } } + interface I516 { } + class S516 : I516 { public S516(I515 s) { } } + interface I517 { } + class S517 : I517 { public S517(I516 s) { } } + interface I518 { } + class S518 : I518 { public S518(I517 s) { } } + interface I519 { } + class S519 : I519 { public S519(I518 s) { } } + interface I520 { } + class S520 : I520 { public S520(I519 s) { } } + interface I521 { } + class S521 : I521 { public S521(I520 s) { } } + interface I522 { } + class S522 : I522 { public S522(I521 s) { } } + interface I523 { } + class S523 : I523 { public S523(I522 s) { } } + interface I524 { } + class S524 : I524 { public S524(I523 s) { } } + interface I525 { } + class S525 : I525 { public S525(I524 s) { } } + interface I526 { } + class S526 : I526 { public S526(I525 s) { } } + interface I527 { } + class S527 : I527 { public S527(I526 s) { } } + interface I528 { } + class S528 : I528 { public S528(I527 s) { } } + interface I529 { } + class S529 : I529 { public S529(I528 s) { } } + interface I530 { } + class S530 : I530 { public S530(I529 s) { } } + interface I531 { } + class S531 : I531 { public S531(I530 s) { } } + interface I532 { } + class S532 : I532 { public S532(I531 s) { } } + interface I533 { } + class S533 : I533 { public S533(I532 s) { } } + interface I534 { } + class S534 : I534 { public S534(I533 s) { } } + interface I535 { } + class S535 : I535 { public S535(I534 s) { } } + interface I536 { } + class S536 : I536 { public S536(I535 s) { } } + interface I537 { } + class S537 : I537 { public S537(I536 s) { } } + interface I538 { } + class S538 : I538 { public S538(I537 s) { } } + interface I539 { } + class S539 : I539 { public S539(I538 s) { } } + interface I540 { } + class S540 : I540 { public S540(I539 s) { } } + interface I541 { } + class S541 : I541 { public S541(I540 s) { } } + interface I542 { } + class S542 : I542 { public S542(I541 s) { } } + interface I543 { } + class S543 : I543 { public S543(I542 s) { } } + interface I544 { } + class S544 : I544 { public S544(I543 s) { } } + interface I545 { } + class S545 : I545 { public S545(I544 s) { } } + interface I546 { } + class S546 : I546 { public S546(I545 s) { } } + interface I547 { } + class S547 : I547 { public S547(I546 s) { } } + interface I548 { } + class S548 : I548 { public S548(I547 s) { } } + interface I549 { } + class S549 : I549 { public S549(I548 s) { } } + interface I550 { } + class S550 : I550 { public S550(I549 s) { } } + interface I551 { } + class S551 : I551 { public S551(I550 s) { } } + interface I552 { } + class S552 : I552 { public S552(I551 s) { } } + interface I553 { } + class S553 : I553 { public S553(I552 s) { } } + interface I554 { } + class S554 : I554 { public S554(I553 s) { } } + interface I555 { } + class S555 : I555 { public S555(I554 s) { } } + interface I556 { } + class S556 : I556 { public S556(I555 s) { } } + interface I557 { } + class S557 : I557 { public S557(I556 s) { } } + interface I558 { } + class S558 : I558 { public S558(I557 s) { } } + interface I559 { } + class S559 : I559 { public S559(I558 s) { } } + interface I560 { } + class S560 : I560 { public S560(I559 s) { } } + interface I561 { } + class S561 : I561 { public S561(I560 s) { } } + interface I562 { } + class S562 : I562 { public S562(I561 s) { } } + interface I563 { } + class S563 : I563 { public S563(I562 s) { } } + interface I564 { } + class S564 : I564 { public S564(I563 s) { } } + interface I565 { } + class S565 : I565 { public S565(I564 s) { } } + interface I566 { } + class S566 : I566 { public S566(I565 s) { } } + interface I567 { } + class S567 : I567 { public S567(I566 s) { } } + interface I568 { } + class S568 : I568 { public S568(I567 s) { } } + interface I569 { } + class S569 : I569 { public S569(I568 s) { } } + interface I570 { } + class S570 : I570 { public S570(I569 s) { } } + interface I571 { } + class S571 : I571 { public S571(I570 s) { } } + interface I572 { } + class S572 : I572 { public S572(I571 s) { } } + interface I573 { } + class S573 : I573 { public S573(I572 s) { } } + interface I574 { } + class S574 : I574 { public S574(I573 s) { } } + interface I575 { } + class S575 : I575 { public S575(I574 s) { } } + interface I576 { } + class S576 : I576 { public S576(I575 s) { } } + interface I577 { } + class S577 : I577 { public S577(I576 s) { } } + interface I578 { } + class S578 : I578 { public S578(I577 s) { } } + interface I579 { } + class S579 : I579 { public S579(I578 s) { } } + interface I580 { } + class S580 : I580 { public S580(I579 s) { } } + interface I581 { } + class S581 : I581 { public S581(I580 s) { } } + interface I582 { } + class S582 : I582 { public S582(I581 s) { } } + interface I583 { } + class S583 : I583 { public S583(I582 s) { } } + interface I584 { } + class S584 : I584 { public S584(I583 s) { } } + interface I585 { } + class S585 : I585 { public S585(I584 s) { } } + interface I586 { } + class S586 : I586 { public S586(I585 s) { } } + interface I587 { } + class S587 : I587 { public S587(I586 s) { } } + interface I588 { } + class S588 : I588 { public S588(I587 s) { } } + interface I589 { } + class S589 : I589 { public S589(I588 s) { } } + interface I590 { } + class S590 : I590 { public S590(I589 s) { } } + interface I591 { } + class S591 : I591 { public S591(I590 s) { } } + interface I592 { } + class S592 : I592 { public S592(I591 s) { } } + interface I593 { } + class S593 : I593 { public S593(I592 s) { } } + interface I594 { } + class S594 : I594 { public S594(I593 s) { } } + interface I595 { } + class S595 : I595 { public S595(I594 s) { } } + interface I596 { } + class S596 : I596 { public S596(I595 s) { } } + interface I597 { } + class S597 : I597 { public S597(I596 s) { } } + interface I598 { } + class S598 : I598 { public S598(I597 s) { } } + interface I599 { } + class S599 : I599 { public S599(I598 s) { } } + interface I600 { } + class S600 : I600 { public S600(I599 s) { } } + interface I601 { } + class S601 : I601 { public S601(I600 s) { } } + interface I602 { } + class S602 : I602 { public S602(I601 s) { } } + interface I603 { } + class S603 : I603 { public S603(I602 s) { } } + interface I604 { } + class S604 : I604 { public S604(I603 s) { } } + interface I605 { } + class S605 : I605 { public S605(I604 s) { } } + interface I606 { } + class S606 : I606 { public S606(I605 s) { } } + interface I607 { } + class S607 : I607 { public S607(I606 s) { } } + interface I608 { } + class S608 : I608 { public S608(I607 s) { } } + interface I609 { } + class S609 : I609 { public S609(I608 s) { } } + interface I610 { } + class S610 : I610 { public S610(I609 s) { } } + interface I611 { } + class S611 : I611 { public S611(I610 s) { } } + interface I612 { } + class S612 : I612 { public S612(I611 s) { } } + interface I613 { } + class S613 : I613 { public S613(I612 s) { } } + interface I614 { } + class S614 : I614 { public S614(I613 s) { } } + interface I615 { } + class S615 : I615 { public S615(I614 s) { } } + interface I616 { } + class S616 : I616 { public S616(I615 s) { } } + interface I617 { } + class S617 : I617 { public S617(I616 s) { } } + interface I618 { } + class S618 : I618 { public S618(I617 s) { } } + interface I619 { } + class S619 : I619 { public S619(I618 s) { } } + interface I620 { } + class S620 : I620 { public S620(I619 s) { } } + interface I621 { } + class S621 : I621 { public S621(I620 s) { } } + interface I622 { } + class S622 : I622 { public S622(I621 s) { } } + interface I623 { } + class S623 : I623 { public S623(I622 s) { } } + interface I624 { } + class S624 : I624 { public S624(I623 s) { } } + interface I625 { } + class S625 : I625 { public S625(I624 s) { } } + interface I626 { } + class S626 : I626 { public S626(I625 s) { } } + interface I627 { } + class S627 : I627 { public S627(I626 s) { } } + interface I628 { } + class S628 : I628 { public S628(I627 s) { } } + interface I629 { } + class S629 : I629 { public S629(I628 s) { } } + interface I630 { } + class S630 : I630 { public S630(I629 s) { } } + interface I631 { } + class S631 : I631 { public S631(I630 s) { } } + interface I632 { } + class S632 : I632 { public S632(I631 s) { } } + interface I633 { } + class S633 : I633 { public S633(I632 s) { } } + interface I634 { } + class S634 : I634 { public S634(I633 s) { } } + interface I635 { } + class S635 : I635 { public S635(I634 s) { } } + interface I636 { } + class S636 : I636 { public S636(I635 s) { } } + interface I637 { } + class S637 : I637 { public S637(I636 s) { } } + interface I638 { } + class S638 : I638 { public S638(I637 s) { } } + interface I639 { } + class S639 : I639 { public S639(I638 s) { } } + interface I640 { } + class S640 : I640 { public S640(I639 s) { } } + interface I641 { } + class S641 : I641 { public S641(I640 s) { } } + interface I642 { } + class S642 : I642 { public S642(I641 s) { } } + interface I643 { } + class S643 : I643 { public S643(I642 s) { } } + interface I644 { } + class S644 : I644 { public S644(I643 s) { } } + interface I645 { } + class S645 : I645 { public S645(I644 s) { } } + interface I646 { } + class S646 : I646 { public S646(I645 s) { } } + interface I647 { } + class S647 : I647 { public S647(I646 s) { } } + interface I648 { } + class S648 : I648 { public S648(I647 s) { } } + interface I649 { } + class S649 : I649 { public S649(I648 s) { } } + interface I650 { } + class S650 : I650 { public S650(I649 s) { } } + interface I651 { } + class S651 : I651 { public S651(I650 s) { } } + interface I652 { } + class S652 : I652 { public S652(I651 s) { } } + interface I653 { } + class S653 : I653 { public S653(I652 s) { } } + interface I654 { } + class S654 : I654 { public S654(I653 s) { } } + interface I655 { } + class S655 : I655 { public S655(I654 s) { } } + interface I656 { } + class S656 : I656 { public S656(I655 s) { } } + interface I657 { } + class S657 : I657 { public S657(I656 s) { } } + interface I658 { } + class S658 : I658 { public S658(I657 s) { } } + interface I659 { } + class S659 : I659 { public S659(I658 s) { } } + interface I660 { } + class S660 : I660 { public S660(I659 s) { } } + interface I661 { } + class S661 : I661 { public S661(I660 s) { } } + interface I662 { } + class S662 : I662 { public S662(I661 s) { } } + interface I663 { } + class S663 : I663 { public S663(I662 s) { } } + interface I664 { } + class S664 : I664 { public S664(I663 s) { } } + interface I665 { } + class S665 : I665 { public S665(I664 s) { } } + interface I666 { } + class S666 : I666 { public S666(I665 s) { } } + interface I667 { } + class S667 : I667 { public S667(I666 s) { } } + interface I668 { } + class S668 : I668 { public S668(I667 s) { } } + interface I669 { } + class S669 : I669 { public S669(I668 s) { } } + interface I670 { } + class S670 : I670 { public S670(I669 s) { } } + interface I671 { } + class S671 : I671 { public S671(I670 s) { } } + interface I672 { } + class S672 : I672 { public S672(I671 s) { } } + interface I673 { } + class S673 : I673 { public S673(I672 s) { } } + interface I674 { } + class S674 : I674 { public S674(I673 s) { } } + interface I675 { } + class S675 : I675 { public S675(I674 s) { } } + interface I676 { } + class S676 : I676 { public S676(I675 s) { } } + interface I677 { } + class S677 : I677 { public S677(I676 s) { } } + interface I678 { } + class S678 : I678 { public S678(I677 s) { } } + interface I679 { } + class S679 : I679 { public S679(I678 s) { } } + interface I680 { } + class S680 : I680 { public S680(I679 s) { } } + interface I681 { } + class S681 : I681 { public S681(I680 s) { } } + interface I682 { } + class S682 : I682 { public S682(I681 s) { } } + interface I683 { } + class S683 : I683 { public S683(I682 s) { } } + interface I684 { } + class S684 : I684 { public S684(I683 s) { } } + interface I685 { } + class S685 : I685 { public S685(I684 s) { } } + interface I686 { } + class S686 : I686 { public S686(I685 s) { } } + interface I687 { } + class S687 : I687 { public S687(I686 s) { } } + interface I688 { } + class S688 : I688 { public S688(I687 s) { } } + interface I689 { } + class S689 : I689 { public S689(I688 s) { } } + interface I690 { } + class S690 : I690 { public S690(I689 s) { } } + interface I691 { } + class S691 : I691 { public S691(I690 s) { } } + interface I692 { } + class S692 : I692 { public S692(I691 s) { } } + interface I693 { } + class S693 : I693 { public S693(I692 s) { } } + interface I694 { } + class S694 : I694 { public S694(I693 s) { } } + interface I695 { } + class S695 : I695 { public S695(I694 s) { } } + interface I696 { } + class S696 : I696 { public S696(I695 s) { } } + interface I697 { } + class S697 : I697 { public S697(I696 s) { } } + interface I698 { } + class S698 : I698 { public S698(I697 s) { } } + interface I699 { } + class S699 : I699 { public S699(I698 s) { } } + interface I700 { } + class S700 : I700 { public S700(I699 s) { } } + interface I701 { } + class S701 : I701 { public S701(I700 s) { } } + interface I702 { } + class S702 : I702 { public S702(I701 s) { } } + interface I703 { } + class S703 : I703 { public S703(I702 s) { } } + interface I704 { } + class S704 : I704 { public S704(I703 s) { } } + interface I705 { } + class S705 : I705 { public S705(I704 s) { } } + interface I706 { } + class S706 : I706 { public S706(I705 s) { } } + interface I707 { } + class S707 : I707 { public S707(I706 s) { } } + interface I708 { } + class S708 : I708 { public S708(I707 s) { } } + interface I709 { } + class S709 : I709 { public S709(I708 s) { } } + interface I710 { } + class S710 : I710 { public S710(I709 s) { } } + interface I711 { } + class S711 : I711 { public S711(I710 s) { } } + interface I712 { } + class S712 : I712 { public S712(I711 s) { } } + interface I713 { } + class S713 : I713 { public S713(I712 s) { } } + interface I714 { } + class S714 : I714 { public S714(I713 s) { } } + interface I715 { } + class S715 : I715 { public S715(I714 s) { } } + interface I716 { } + class S716 : I716 { public S716(I715 s) { } } + interface I717 { } + class S717 : I717 { public S717(I716 s) { } } + interface I718 { } + class S718 : I718 { public S718(I717 s) { } } + interface I719 { } + class S719 : I719 { public S719(I718 s) { } } + interface I720 { } + class S720 : I720 { public S720(I719 s) { } } + interface I721 { } + class S721 : I721 { public S721(I720 s) { } } + interface I722 { } + class S722 : I722 { public S722(I721 s) { } } + interface I723 { } + class S723 : I723 { public S723(I722 s) { } } + interface I724 { } + class S724 : I724 { public S724(I723 s) { } } + interface I725 { } + class S725 : I725 { public S725(I724 s) { } } + interface I726 { } + class S726 : I726 { public S726(I725 s) { } } + interface I727 { } + class S727 : I727 { public S727(I726 s) { } } + interface I728 { } + class S728 : I728 { public S728(I727 s) { } } + interface I729 { } + class S729 : I729 { public S729(I728 s) { } } + interface I730 { } + class S730 : I730 { public S730(I729 s) { } } + interface I731 { } + class S731 : I731 { public S731(I730 s) { } } + interface I732 { } + class S732 : I732 { public S732(I731 s) { } } + interface I733 { } + class S733 : I733 { public S733(I732 s) { } } + interface I734 { } + class S734 : I734 { public S734(I733 s) { } } + interface I735 { } + class S735 : I735 { public S735(I734 s) { } } + interface I736 { } + class S736 : I736 { public S736(I735 s) { } } + interface I737 { } + class S737 : I737 { public S737(I736 s) { } } + interface I738 { } + class S738 : I738 { public S738(I737 s) { } } + interface I739 { } + class S739 : I739 { public S739(I738 s) { } } + interface I740 { } + class S740 : I740 { public S740(I739 s) { } } + interface I741 { } + class S741 : I741 { public S741(I740 s) { } } + interface I742 { } + class S742 : I742 { public S742(I741 s) { } } + interface I743 { } + class S743 : I743 { public S743(I742 s) { } } + interface I744 { } + class S744 : I744 { public S744(I743 s) { } } + interface I745 { } + class S745 : I745 { public S745(I744 s) { } } + interface I746 { } + class S746 : I746 { public S746(I745 s) { } } + interface I747 { } + class S747 : I747 { public S747(I746 s) { } } + interface I748 { } + class S748 : I748 { public S748(I747 s) { } } + interface I749 { } + class S749 : I749 { public S749(I748 s) { } } + interface I750 { } + class S750 : I750 { public S750(I749 s) { } } + interface I751 { } + class S751 : I751 { public S751(I750 s) { } } + interface I752 { } + class S752 : I752 { public S752(I751 s) { } } + interface I753 { } + class S753 : I753 { public S753(I752 s) { } } + interface I754 { } + class S754 : I754 { public S754(I753 s) { } } + interface I755 { } + class S755 : I755 { public S755(I754 s) { } } + interface I756 { } + class S756 : I756 { public S756(I755 s) { } } + interface I757 { } + class S757 : I757 { public S757(I756 s) { } } + interface I758 { } + class S758 : I758 { public S758(I757 s) { } } + interface I759 { } + class S759 : I759 { public S759(I758 s) { } } + interface I760 { } + class S760 : I760 { public S760(I759 s) { } } + interface I761 { } + class S761 : I761 { public S761(I760 s) { } } + interface I762 { } + class S762 : I762 { public S762(I761 s) { } } + interface I763 { } + class S763 : I763 { public S763(I762 s) { } } + interface I764 { } + class S764 : I764 { public S764(I763 s) { } } + interface I765 { } + class S765 : I765 { public S765(I764 s) { } } + interface I766 { } + class S766 : I766 { public S766(I765 s) { } } + interface I767 { } + class S767 : I767 { public S767(I766 s) { } } + interface I768 { } + class S768 : I768 { public S768(I767 s) { } } + interface I769 { } + class S769 : I769 { public S769(I768 s) { } } + interface I770 { } + class S770 : I770 { public S770(I769 s) { } } + interface I771 { } + class S771 : I771 { public S771(I770 s) { } } + interface I772 { } + class S772 : I772 { public S772(I771 s) { } } + interface I773 { } + class S773 : I773 { public S773(I772 s) { } } + interface I774 { } + class S774 : I774 { public S774(I773 s) { } } + interface I775 { } + class S775 : I775 { public S775(I774 s) { } } + interface I776 { } + class S776 : I776 { public S776(I775 s) { } } + interface I777 { } + class S777 : I777 { public S777(I776 s) { } } + interface I778 { } + class S778 : I778 { public S778(I777 s) { } } + interface I779 { } + class S779 : I779 { public S779(I778 s) { } } + interface I780 { } + class S780 : I780 { public S780(I779 s) { } } + interface I781 { } + class S781 : I781 { public S781(I780 s) { } } + interface I782 { } + class S782 : I782 { public S782(I781 s) { } } + interface I783 { } + class S783 : I783 { public S783(I782 s) { } } + interface I784 { } + class S784 : I784 { public S784(I783 s) { } } + interface I785 { } + class S785 : I785 { public S785(I784 s) { } } + interface I786 { } + class S786 : I786 { public S786(I785 s) { } } + interface I787 { } + class S787 : I787 { public S787(I786 s) { } } + interface I788 { } + class S788 : I788 { public S788(I787 s) { } } + interface I789 { } + class S789 : I789 { public S789(I788 s) { } } + interface I790 { } + class S790 : I790 { public S790(I789 s) { } } + interface I791 { } + class S791 : I791 { public S791(I790 s) { } } + interface I792 { } + class S792 : I792 { public S792(I791 s) { } } + interface I793 { } + class S793 : I793 { public S793(I792 s) { } } + interface I794 { } + class S794 : I794 { public S794(I793 s) { } } + interface I795 { } + class S795 : I795 { public S795(I794 s) { } } + interface I796 { } + class S796 : I796 { public S796(I795 s) { } } + interface I797 { } + class S797 : I797 { public S797(I796 s) { } } + interface I798 { } + class S798 : I798 { public S798(I797 s) { } } + interface I799 { } + class S799 : I799 { public S799(I798 s) { } } + interface I800 { } + class S800 : I800 { public S800(I799 s) { } } + interface I801 { } + class S801 : I801 { public S801(I800 s) { } } + interface I802 { } + class S802 : I802 { public S802(I801 s) { } } + interface I803 { } + class S803 : I803 { public S803(I802 s) { } } + interface I804 { } + class S804 : I804 { public S804(I803 s) { } } + interface I805 { } + class S805 : I805 { public S805(I804 s) { } } + interface I806 { } + class S806 : I806 { public S806(I805 s) { } } + interface I807 { } + class S807 : I807 { public S807(I806 s) { } } + interface I808 { } + class S808 : I808 { public S808(I807 s) { } } + interface I809 { } + class S809 : I809 { public S809(I808 s) { } } + interface I810 { } + class S810 : I810 { public S810(I809 s) { } } + interface I811 { } + class S811 : I811 { public S811(I810 s) { } } + interface I812 { } + class S812 : I812 { public S812(I811 s) { } } + interface I813 { } + class S813 : I813 { public S813(I812 s) { } } + interface I814 { } + class S814 : I814 { public S814(I813 s) { } } + interface I815 { } + class S815 : I815 { public S815(I814 s) { } } + interface I816 { } + class S816 : I816 { public S816(I815 s) { } } + interface I817 { } + class S817 : I817 { public S817(I816 s) { } } + interface I818 { } + class S818 : I818 { public S818(I817 s) { } } + interface I819 { } + class S819 : I819 { public S819(I818 s) { } } + interface I820 { } + class S820 : I820 { public S820(I819 s) { } } + interface I821 { } + class S821 : I821 { public S821(I820 s) { } } + interface I822 { } + class S822 : I822 { public S822(I821 s) { } } + interface I823 { } + class S823 : I823 { public S823(I822 s) { } } + interface I824 { } + class S824 : I824 { public S824(I823 s) { } } + interface I825 { } + class S825 : I825 { public S825(I824 s) { } } + interface I826 { } + class S826 : I826 { public S826(I825 s) { } } + interface I827 { } + class S827 : I827 { public S827(I826 s) { } } + interface I828 { } + class S828 : I828 { public S828(I827 s) { } } + interface I829 { } + class S829 : I829 { public S829(I828 s) { } } + interface I830 { } + class S830 : I830 { public S830(I829 s) { } } + interface I831 { } + class S831 : I831 { public S831(I830 s) { } } + interface I832 { } + class S832 : I832 { public S832(I831 s) { } } + interface I833 { } + class S833 : I833 { public S833(I832 s) { } } + interface I834 { } + class S834 : I834 { public S834(I833 s) { } } + interface I835 { } + class S835 : I835 { public S835(I834 s) { } } + interface I836 { } + class S836 : I836 { public S836(I835 s) { } } + interface I837 { } + class S837 : I837 { public S837(I836 s) { } } + interface I838 { } + class S838 : I838 { public S838(I837 s) { } } + interface I839 { } + class S839 : I839 { public S839(I838 s) { } } + interface I840 { } + class S840 : I840 { public S840(I839 s) { } } + interface I841 { } + class S841 : I841 { public S841(I840 s) { } } + interface I842 { } + class S842 : I842 { public S842(I841 s) { } } + interface I843 { } + class S843 : I843 { public S843(I842 s) { } } + interface I844 { } + class S844 : I844 { public S844(I843 s) { } } + interface I845 { } + class S845 : I845 { public S845(I844 s) { } } + interface I846 { } + class S846 : I846 { public S846(I845 s) { } } + interface I847 { } + class S847 : I847 { public S847(I846 s) { } } + interface I848 { } + class S848 : I848 { public S848(I847 s) { } } + interface I849 { } + class S849 : I849 { public S849(I848 s) { } } + interface I850 { } + class S850 : I850 { public S850(I849 s) { } } + interface I851 { } + class S851 : I851 { public S851(I850 s) { } } + interface I852 { } + class S852 : I852 { public S852(I851 s) { } } + interface I853 { } + class S853 : I853 { public S853(I852 s) { } } + interface I854 { } + class S854 : I854 { public S854(I853 s) { } } + interface I855 { } + class S855 : I855 { public S855(I854 s) { } } + interface I856 { } + class S856 : I856 { public S856(I855 s) { } } + interface I857 { } + class S857 : I857 { public S857(I856 s) { } } + interface I858 { } + class S858 : I858 { public S858(I857 s) { } } + interface I859 { } + class S859 : I859 { public S859(I858 s) { } } + interface I860 { } + class S860 : I860 { public S860(I859 s) { } } + interface I861 { } + class S861 : I861 { public S861(I860 s) { } } + interface I862 { } + class S862 : I862 { public S862(I861 s) { } } + interface I863 { } + class S863 : I863 { public S863(I862 s) { } } + interface I864 { } + class S864 : I864 { public S864(I863 s) { } } + interface I865 { } + class S865 : I865 { public S865(I864 s) { } } + interface I866 { } + class S866 : I866 { public S866(I865 s) { } } + interface I867 { } + class S867 : I867 { public S867(I866 s) { } } + interface I868 { } + class S868 : I868 { public S868(I867 s) { } } + interface I869 { } + class S869 : I869 { public S869(I868 s) { } } + interface I870 { } + class S870 : I870 { public S870(I869 s) { } } + interface I871 { } + class S871 : I871 { public S871(I870 s) { } } + interface I872 { } + class S872 : I872 { public S872(I871 s) { } } + interface I873 { } + class S873 : I873 { public S873(I872 s) { } } + interface I874 { } + class S874 : I874 { public S874(I873 s) { } } + interface I875 { } + class S875 : I875 { public S875(I874 s) { } } + interface I876 { } + class S876 : I876 { public S876(I875 s) { } } + interface I877 { } + class S877 : I877 { public S877(I876 s) { } } + interface I878 { } + class S878 : I878 { public S878(I877 s) { } } + interface I879 { } + class S879 : I879 { public S879(I878 s) { } } + interface I880 { } + class S880 : I880 { public S880(I879 s) { } } + interface I881 { } + class S881 : I881 { public S881(I880 s) { } } + interface I882 { } + class S882 : I882 { public S882(I881 s) { } } + interface I883 { } + class S883 : I883 { public S883(I882 s) { } } + interface I884 { } + class S884 : I884 { public S884(I883 s) { } } + interface I885 { } + class S885 : I885 { public S885(I884 s) { } } + interface I886 { } + class S886 : I886 { public S886(I885 s) { } } + interface I887 { } + class S887 : I887 { public S887(I886 s) { } } + interface I888 { } + class S888 : I888 { public S888(I887 s) { } } + interface I889 { } + class S889 : I889 { public S889(I888 s) { } } + interface I890 { } + class S890 : I890 { public S890(I889 s) { } } + interface I891 { } + class S891 : I891 { public S891(I890 s) { } } + interface I892 { } + class S892 : I892 { public S892(I891 s) { } } + interface I893 { } + class S893 : I893 { public S893(I892 s) { } } + interface I894 { } + class S894 : I894 { public S894(I893 s) { } } + interface I895 { } + class S895 : I895 { public S895(I894 s) { } } + interface I896 { } + class S896 : I896 { public S896(I895 s) { } } + interface I897 { } + class S897 : I897 { public S897(I896 s) { } } + interface I898 { } + class S898 : I898 { public S898(I897 s) { } } + interface I899 { } + class S899 : I899 { public S899(I898 s) { } } + interface I900 { } + class S900 : I900 { public S900(I899 s) { } } + interface I901 { } + class S901 : I901 { public S901(I900 s) { } } + interface I902 { } + class S902 : I902 { public S902(I901 s) { } } + interface I903 { } + class S903 : I903 { public S903(I902 s) { } } + interface I904 { } + class S904 : I904 { public S904(I903 s) { } } + interface I905 { } + class S905 : I905 { public S905(I904 s) { } } + interface I906 { } + class S906 : I906 { public S906(I905 s) { } } + interface I907 { } + class S907 : I907 { public S907(I906 s) { } } + interface I908 { } + class S908 : I908 { public S908(I907 s) { } } + interface I909 { } + class S909 : I909 { public S909(I908 s) { } } + interface I910 { } + class S910 : I910 { public S910(I909 s) { } } + interface I911 { } + class S911 : I911 { public S911(I910 s) { } } + interface I912 { } + class S912 : I912 { public S912(I911 s) { } } + interface I913 { } + class S913 : I913 { public S913(I912 s) { } } + interface I914 { } + class S914 : I914 { public S914(I913 s) { } } + interface I915 { } + class S915 : I915 { public S915(I914 s) { } } + interface I916 { } + class S916 : I916 { public S916(I915 s) { } } + interface I917 { } + class S917 : I917 { public S917(I916 s) { } } + interface I918 { } + class S918 : I918 { public S918(I917 s) { } } + interface I919 { } + class S919 : I919 { public S919(I918 s) { } } + interface I920 { } + class S920 : I920 { public S920(I919 s) { } } + interface I921 { } + class S921 : I921 { public S921(I920 s) { } } + interface I922 { } + class S922 : I922 { public S922(I921 s) { } } + interface I923 { } + class S923 : I923 { public S923(I922 s) { } } + interface I924 { } + class S924 : I924 { public S924(I923 s) { } } + interface I925 { } + class S925 : I925 { public S925(I924 s) { } } + interface I926 { } + class S926 : I926 { public S926(I925 s) { } } + interface I927 { } + class S927 : I927 { public S927(I926 s) { } } + interface I928 { } + class S928 : I928 { public S928(I927 s) { } } + interface I929 { } + class S929 : I929 { public S929(I928 s) { } } + interface I930 { } + class S930 : I930 { public S930(I929 s) { } } + interface I931 { } + class S931 : I931 { public S931(I930 s) { } } + interface I932 { } + class S932 : I932 { public S932(I931 s) { } } + interface I933 { } + class S933 : I933 { public S933(I932 s) { } } + interface I934 { } + class S934 : I934 { public S934(I933 s) { } } + interface I935 { } + class S935 : I935 { public S935(I934 s) { } } + interface I936 { } + class S936 : I936 { public S936(I935 s) { } } + interface I937 { } + class S937 : I937 { public S937(I936 s) { } } + interface I938 { } + class S938 : I938 { public S938(I937 s) { } } + interface I939 { } + class S939 : I939 { public S939(I938 s) { } } + interface I940 { } + class S940 : I940 { public S940(I939 s) { } } + interface I941 { } + class S941 : I941 { public S941(I940 s) { } } + interface I942 { } + class S942 : I942 { public S942(I941 s) { } } + interface I943 { } + class S943 : I943 { public S943(I942 s) { } } + interface I944 { } + class S944 : I944 { public S944(I943 s) { } } + interface I945 { } + class S945 : I945 { public S945(I944 s) { } } + interface I946 { } + class S946 : I946 { public S946(I945 s) { } } + interface I947 { } + class S947 : I947 { public S947(I946 s) { } } + interface I948 { } + class S948 : I948 { public S948(I947 s) { } } + interface I949 { } + class S949 : I949 { public S949(I948 s) { } } + interface I950 { } + class S950 : I950 { public S950(I949 s) { } } + interface I951 { } + class S951 : I951 { public S951(I950 s) { } } + interface I952 { } + class S952 : I952 { public S952(I951 s) { } } + interface I953 { } + class S953 : I953 { public S953(I952 s) { } } + interface I954 { } + class S954 : I954 { public S954(I953 s) { } } + interface I955 { } + class S955 : I955 { public S955(I954 s) { } } + interface I956 { } + class S956 : I956 { public S956(I955 s) { } } + interface I957 { } + class S957 : I957 { public S957(I956 s) { } } + interface I958 { } + class S958 : I958 { public S958(I957 s) { } } + interface I959 { } + class S959 : I959 { public S959(I958 s) { } } + interface I960 { } + class S960 : I960 { public S960(I959 s) { } } + interface I961 { } + class S961 : I961 { public S961(I960 s) { } } + interface I962 { } + class S962 : I962 { public S962(I961 s) { } } + interface I963 { } + class S963 : I963 { public S963(I962 s) { } } + interface I964 { } + class S964 : I964 { public S964(I963 s) { } } + interface I965 { } + class S965 : I965 { public S965(I964 s) { } } + interface I966 { } + class S966 : I966 { public S966(I965 s) { } } + interface I967 { } + class S967 : I967 { public S967(I966 s) { } } + interface I968 { } + class S968 : I968 { public S968(I967 s) { } } + interface I969 { } + class S969 : I969 { public S969(I968 s) { } } + interface I970 { } + class S970 : I970 { public S970(I969 s) { } } + interface I971 { } + class S971 : I971 { public S971(I970 s) { } } + interface I972 { } + class S972 : I972 { public S972(I971 s) { } } + interface I973 { } + class S973 : I973 { public S973(I972 s) { } } + interface I974 { } + class S974 : I974 { public S974(I973 s) { } } + interface I975 { } + class S975 : I975 { public S975(I974 s) { } } + interface I976 { } + class S976 : I976 { public S976(I975 s) { } } + interface I977 { } + class S977 : I977 { public S977(I976 s) { } } + interface I978 { } + class S978 : I978 { public S978(I977 s) { } } + interface I979 { } + class S979 : I979 { public S979(I978 s) { } } + interface I980 { } + class S980 : I980 { public S980(I979 s) { } } + interface I981 { } + class S981 : I981 { public S981(I980 s) { } } + interface I982 { } + class S982 : I982 { public S982(I981 s) { } } + interface I983 { } + class S983 : I983 { public S983(I982 s) { } } + interface I984 { } + class S984 : I984 { public S984(I983 s) { } } + interface I985 { } + class S985 : I985 { public S985(I984 s) { } } + interface I986 { } + class S986 : I986 { public S986(I985 s) { } } + interface I987 { } + class S987 : I987 { public S987(I986 s) { } } + interface I988 { } + class S988 : I988 { public S988(I987 s) { } } + interface I989 { } + class S989 : I989 { public S989(I988 s) { } } + interface I990 { } + class S990 : I990 { public S990(I989 s) { } } + interface I991 { } + class S991 : I991 { public S991(I990 s) { } } + interface I992 { } + class S992 : I992 { public S992(I991 s) { } } + interface I993 { } + class S993 : I993 { public S993(I992 s) { } } + interface I994 { } + class S994 : I994 { public S994(I993 s) { } } + interface I995 { } + class S995 : I995 { public S995(I994 s) { } } + interface I996 { } + class S996 : I996 { public S996(I995 s) { } } + interface I997 { } + class S997 : I997 { public S997(I996 s) { } } + interface I998 { } + class S998 : I998 { public S998(I997 s) { } } + interface I999 { } + class S999 : I999 { public S999(I998 s) { } } + public static class CompilationTestDataProvider + { + public static void Register(IServiceCollection p) + { + p.AddScoped(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddTransient(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddScoped(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + p.AddSingleton(); + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderContainerTests.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderContainerTests.cs new file mode 100644 index 00000000000..e2109d8c69e --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderContainerTests.cs @@ -0,0 +1,212 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using Microsoft.Extensions.DependencyInjection.Fakes; +using Microsoft.Extensions.DependencyInjection.Specification; +using Microsoft.Extensions.DependencyInjection.Specification.Fakes; +using Microsoft.Extensions.DependencyInjection.Tests.Fakes; +using Xunit; + +namespace Microsoft.Extensions.DependencyInjection.Tests +{ + public abstract class ServiceProviderContainerTests : DependencyInjectionSpecificationTests + { + [Fact] + public void RethrowOriginalExceptionFromConstructor() + { + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(); + serviceCollection.AddTransient(); + serviceCollection.AddTransient(); + + var provider = CreateServiceProvider(serviceCollection); + + var ex1 = Assert.Throws(() => provider.GetService()); + Assert.Equal(nameof(ClassWithThrowingEmptyCtor), ex1.Message); + + var ex2 = Assert.Throws(() => provider.GetService()); + Assert.Equal(nameof(ClassWithThrowingCtor), ex2.Message); + } + + [Fact] + public void DependencyWithPrivateConstructorIsIdentifiedAsPartOfException() + { + // Arrange + var expectedMessage = $"A suitable constructor for type '{typeof(ClassWithPrivateCtor).FullName}' could not be located. " + + "Ensure the type is concrete and services are registered for all parameters of a public constructor."; + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(); + serviceCollection.AddTransient(); + var serviceProvider = CreateServiceProvider(serviceCollection); + + // Act and Assert + var ex = Assert.Throws(() => serviceProvider.GetServices()); + Assert.Equal(expectedMessage, ex.Message); + } + + [Fact] + public void AttemptingToResolveNonexistentServiceIndirectlyThrows() + { + // Arrange + var collection = new ServiceCollection(); + collection.AddTransient(); + var provider = CreateServiceProvider(collection); + + // Act and Assert + var ex = Assert.Throws(() => provider.GetService()); + Assert.Equal($"Unable to resolve service for type '{typeof(IFakeService)}' while attempting to activate " + + $"'{typeof(DependOnNonexistentService)}'.", ex.Message); + } + + [Fact] + public void AttemptingToIEnumerableResolveNonexistentServiceIndirectlyThrows() + { + // Arrange + var collection = new ServiceCollection(); + collection.AddTransient(); + var provider = CreateServiceProvider(collection); + + // Act and Assert + var ex = Assert.Throws(() => + provider.GetService>()); + Assert.Equal($"Unable to resolve service for type '{typeof(IFakeService)}' while attempting to activate " + + $"'{typeof(DependOnNonexistentService)}'.", ex.Message); + } + + [Theory] + // GenericTypeDefintion, Abstract GenericTypeDefintion + [InlineData(typeof(IFakeOpenGenericService<>), typeof(AbstractFakeOpenGenericService<>))] + // GenericTypeDefintion, Interface GenericTypeDefintion + [InlineData(typeof(ICollection<>), typeof(IList<>))] + // Implementation type is GenericTypeDefintion + [InlineData(typeof(IList), typeof(List<>))] + // Implementation type is Abstract + [InlineData(typeof(IFakeService), typeof(AbstractClass))] + // Implementation type is Interface + [InlineData(typeof(IFakeEveryService), typeof(IFakeService))] + public void CreatingServiceProviderWithUnresolvableTypesThrows(Type serviceType, Type implementationType) + { + // Arrange + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(serviceType, implementationType); + + // Act and Assert + var exception = Assert.Throws(() => serviceCollection.BuildServiceProvider()); + Assert.Equal( + $"Cannot instantiate implementation type '{implementationType}' for service type '{serviceType}'.", + exception.Message); + } + + [Fact] + public void DoesNotDisposeSingletonInstances() + { + var disposable = new Disposable(); + var serviceCollection = new ServiceCollection(); + serviceCollection.AddSingleton(disposable); + + var provider = CreateServiceProvider(serviceCollection); + provider.GetService(); + + ((IDisposable)provider).Dispose(); + + Assert.False(disposable.Disposed); + } + + [Fact] + public void ResolvesServiceMixedServiceAndOptionalStructConstructorArguments() + { + var serviceCollection = new ServiceCollection(); + serviceCollection.AddSingleton(); + serviceCollection.AddSingleton(); + + var provider = CreateServiceProvider(serviceCollection); + var service = provider.GetService(); + Assert.NotNull(service); + } + + [Fact] + public void RootProviderDispose_PreventsServiceResolution() + { + var serviceCollection = new ServiceCollection(); + serviceCollection.AddSingleton(); + + var provider = CreateServiceProvider(serviceCollection); + ((IDisposable)provider).Dispose(); + + Assert.Throws(() => provider.GetService()); + } + + [Fact] + public void RootProviderDispose_PreventsScopeCreation() + { + var serviceCollection = new ServiceCollection(); + serviceCollection.AddSingleton(); + + var provider = CreateServiceProvider(serviceCollection); + ((IDisposable)provider).Dispose(); + + Assert.Throws(() => provider.CreateScope()); + } + + [Fact] + public void RootProviderDispose_PreventsServiceResolution_InChildScope() + { + var serviceCollection = new ServiceCollection(); + serviceCollection.AddScoped(); + + var provider = CreateServiceProvider(serviceCollection); + var scope = provider.CreateScope(); + ((IDisposable)provider).Dispose(); + + Assert.Throws(() => scope.ServiceProvider.GetService()); + } + + [Fact] + public void ScopeDispose_PreventsServiceResolution() + { + var serviceCollection = new ServiceCollection(); + serviceCollection.AddScoped(); + + var provider = CreateServiceProvider(serviceCollection); + var scope = provider.CreateScope(); + scope.Dispose(); + + Assert.Throws(() => scope.ServiceProvider.GetService()); + //Check that resolution from root works + Assert.NotNull(provider.CreateScope()); + } + + [Theory(Skip = "We don't support value task services currently")] + [InlineData(ServiceLifetime.Transient)] + [InlineData(ServiceLifetime.Scoped)] + [InlineData(ServiceLifetime.Singleton)] + public void WorksWithStructServices(ServiceLifetime lifetime) + { + IServiceCollection serviceCollection = new ServiceCollection(); + serviceCollection.Add(new ServiceDescriptor(typeof(IFakeService), typeof(StructFakeService), lifetime)); + serviceCollection.Add(new ServiceDescriptor(typeof(StructService), typeof(StructService), lifetime)); + serviceCollection.Add(new ServiceDescriptor(typeof(IFakeMultipleService), typeof(StructFakeMultipleService), lifetime)); + + var provider = CreateServiceProvider(serviceCollection); + var service = provider.GetService(); + Assert.NotNull(service); + } + + private abstract class AbstractFakeOpenGenericService : IFakeOpenGenericService + { + public abstract T Value { get; } + } + + private class Disposable : IDisposable + { + public bool Disposed { get; set; } + + public void Dispose() + { + Disposed = true; + } + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderDynamicContainerTests.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderDynamicContainerTests.cs new file mode 100644 index 00000000000..3e732661e0f --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderDynamicContainerTests.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection.Tests +{ + public class ServiceProviderDynamicContainerTests : ServiceProviderContainerTests + { + protected override IServiceProvider CreateServiceProvider(IServiceCollection collection) => + collection.BuildServiceProvider(); + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderExpressionsContainerTests.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderExpressionsContainerTests.cs new file mode 100644 index 00000000000..2ecad4091f3 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderExpressionsContainerTests.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection.Tests +{ + public class ServiceProviderExpressionsContainerTests : ServiceProviderContainerTests + { + protected override IServiceProvider CreateServiceProvider(IServiceCollection collection) => + collection.BuildServiceProvider(new ServiceProviderOptions { Mode = ServiceProviderMode.Expressions }); + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderILEmitContainerTests.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderILEmitContainerTests.cs new file mode 100644 index 00000000000..2a6fbd0d06b --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderILEmitContainerTests.cs @@ -0,0 +1,13 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.Extensions.DependencyInjection.Tests +{ + public class ServiceProviderILEmitContainerTests : ServiceProviderContainerTests + { + protected override IServiceProvider CreateServiceProvider(IServiceCollection collection) => + collection.BuildServiceProvider(new ServiceProviderOptions() { Mode = ServiceProviderMode.ILEmit}); + } +} \ No newline at end of file diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderServiceExtensionsTest.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderServiceExtensionsTest.cs new file mode 100644 index 00000000000..6520f649d24 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderServiceExtensionsTest.cs @@ -0,0 +1,274 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.AspNetCore.Testing; +using Xunit; + +namespace Microsoft.Extensions.DependencyInjection +{ + public class ServiceProviderExtensionsTest + { + [Fact] + public void GetService_Returns_CorrectService() + { + // Arrange + var serviceProvider = CreateTestServiceProvider(1); + + // Act + var service = serviceProvider.GetService(); + + // Assert + Assert.IsType(service); + } + + [Fact] + public void ISupportRequiredService_GetRequiredService_Returns_CorrectService() + { + // Arrange + var serviceProvider = new RequiredServiceSupportingProvider(); + + // Act + var service = serviceProvider.GetRequiredService(); + + // Assert + Assert.IsType(service); + } + + [Fact] + public void GetRequiredService_Throws_WhenNoServiceRegistered() + { + // Arrange + var serviceProvider = CreateTestServiceProvider(0); + + // Act + Assert + ExceptionAssert.Throws(() => serviceProvider.GetRequiredService(), + $"No service for type '{typeof(IFoo)}' has been registered."); + } + + [Fact] + public void ISupportRequiredService_GetRequiredService_Throws_WhenNoServiceRegistered() + { + // Arrange + var serviceProvider = new RequiredServiceSupportingProvider(); + + // Act + Assert + ExceptionAssert.Throws(() => serviceProvider.GetRequiredService()); + } + + [Fact] + public void NonGeneric_GetRequiredService_Throws_WhenNoServiceRegistered() + { + // Arrange + var serviceProvider = CreateTestServiceProvider(0); + + // Act + Assert + ExceptionAssert.Throws(() => serviceProvider.GetRequiredService(typeof(IFoo)), + $"No service for type '{typeof(IFoo)}' has been registered."); + } + + [Fact] + public void ISupportRequiredService_NonGeneric_GetRequiredService_Throws_WhenNoServiceRegistered() + { + // Arrange + var serviceProvider = new RequiredServiceSupportingProvider(); + + // Act + Assert + ExceptionAssert.Throws(() => serviceProvider.GetRequiredService(typeof(IFoo))); + } + + [Fact] + public void GetServices_Returns_AllServices() + { + // Arrange + var serviceProvider = CreateTestServiceProvider(2); + + // Act + var services = serviceProvider.GetServices(); + + // Assert + Assert.Contains(services, item => item is Foo1); + Assert.Contains(services, item => item is Foo2); + Assert.Equal(2, services.Count()); + } + + [Fact] + public void NonGeneric_GetServices_Returns_AllServices() + { + // Arrange + var serviceProvider = CreateTestServiceProvider(2); + + // Act + var services = serviceProvider.GetServices(typeof(IFoo)); + + // Assert + Assert.Contains(services, item => item is Foo1); + Assert.Contains(services, item => item is Foo2); + Assert.Equal(2, services.Count()); + } + + [Fact] + public void GetServices_Returns_SingleService() + { + // Arrange + var serviceProvider = CreateTestServiceProvider(1); + + // Act + var services = serviceProvider.GetServices(); + + // Assert + var item = Assert.Single(services); + Assert.IsType(item); + } + + [Fact] + public void NonGeneric_GetServices_Returns_SingleService() + { + // Arrange + var serviceProvider = CreateTestServiceProvider(1); + + // Act + var services = serviceProvider.GetServices(typeof(IFoo)); + + // Assert + var item = Assert.Single(services); + Assert.IsType(item); + } + + [Fact] + public void GetServices_Returns_CorrectTypes() + { + // Arrange + var serviceProvider = CreateTestServiceProvider(4); + + // Act + var services = serviceProvider.GetServices(typeof(IBar)); + + // Assert + foreach (var service in services) + { + Assert.IsAssignableFrom(service); + } + Assert.Equal(2, services.Count()); + } + + [Fact] + public void GetServices_Returns_EmptyArray_WhenNoServicesAvailable() + { + // Arrange + var serviceProvider = CreateTestServiceProvider(0); + + // Act + var services = serviceProvider.GetServices(); + + // Assert + Assert.Empty(services); + Assert.IsType(services); + } + + [Fact] + public void NonGeneric_GetServices_Returns_EmptyArray_WhenNoServicesAvailable() + { + // Arrange + var serviceProvider = CreateTestServiceProvider(0); + + // Act + var services = serviceProvider.GetServices(typeof(IFoo)); + + // Assert + Assert.Empty(services); + Assert.IsType(services); + } + + [Fact] + public void GetServices_WithBuildServiceProvider_Returns_EmptyList_WhenNoServicesAvailable() + { + // Arrange + var serviceCollection = new ServiceCollection(); + serviceCollection.AddSingleton>(new List()); + var serviceProvider = serviceCollection.BuildServiceProvider(); + + // Act + var services = serviceProvider.GetServices(); + + // Assert + Assert.Empty(services); + Assert.IsType>(services); + } + + [Fact] + public void NonGeneric_GetServices_WithBuildServiceProvider_Returns_EmptyList_WhenNoServicesAvailable() + { + // Arrange + var serviceCollection = new ServiceCollection(); + serviceCollection.AddSingleton>(new List()); + var serviceProvider = serviceCollection.BuildServiceProvider(); + + // Act + var services = serviceProvider.GetServices(typeof(IFoo)); + + // Assert + Assert.Empty(services); + Assert.IsType>(services); + } + + private static IServiceProvider CreateTestServiceProvider(int count) + { + var serviceCollection = new ServiceCollection(); + + if (count > 0) + { + serviceCollection.AddTransient(); + } + + if (count > 1) + { + serviceCollection.AddTransient(); + } + + if (count > 2) + { + serviceCollection.AddTransient(); + } + + if (count > 3) + { + serviceCollection.AddTransient(); + } + + return serviceCollection.BuildServiceProvider(); + } + + public interface IFoo { } + + public class Foo1 : IFoo { } + + public class Foo2 : IFoo { } + + public interface IBar { } + + public class Bar1 : IBar { } + + public class Bar2 : IBar { } + + private class RequiredServiceSupportingProvider : IServiceProvider, ISupportRequiredService + { + object ISupportRequiredService.GetRequiredService(Type serviceType) + { + if (serviceType == typeof(IBar)) + { + return new Bar1(); + } + + throw new RankException(); + } + + object IServiceProvider.GetService(Type serviceType) + { + throw new NotSupportedException(); + } + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderValidationTests.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderValidationTests.cs new file mode 100644 index 00000000000..ca05f9322f0 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceProviderValidationTests.cs @@ -0,0 +1,157 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using Xunit; + +namespace Microsoft.Extensions.DependencyInjection.Tests +{ + public class ServiceProviderValidationTests + { + [Fact] + public void GetService_Throws_WhenScopedIsInjectedIntoSingleton() + { + // Arrange + var serviceCollection = new ServiceCollection(); + serviceCollection.AddSingleton(); + serviceCollection.AddScoped(); + var serviceProvider = serviceCollection.BuildServiceProvider(validateScopes: true); + + // Act + Assert + var exception = Assert.Throws(() => serviceProvider.GetService(typeof(IFoo))); + Assert.Equal($"Cannot consume scoped service '{typeof(IBar)}' from singleton '{typeof(IFoo)}'.", exception.Message); + } + + [Fact] + public void GetService_Throws_WhenScopedIsInjectedIntoSingletonThroughTransient() + { + // Arrange + var serviceCollection = new ServiceCollection(); + serviceCollection.AddSingleton(); + serviceCollection.AddTransient(); + serviceCollection.AddScoped(); + var serviceProvider = serviceCollection.BuildServiceProvider(validateScopes: true); + + // Act + Assert + var exception = Assert.Throws(() => serviceProvider.GetService(typeof(IFoo))); + Assert.Equal($"Cannot consume scoped service '{typeof(IBaz)}' from singleton '{typeof(IFoo)}'.", exception.Message); + } + + [Fact] + public void GetService_Throws_WhenScopedIsInjectedIntoSingletonThroughSingleton() + { + // Arrange + var serviceCollection = new ServiceCollection(); + serviceCollection.AddSingleton(); + serviceCollection.AddSingleton(); + serviceCollection.AddScoped(); + var serviceProvider = serviceCollection.BuildServiceProvider(validateScopes: true); + + // Act + Assert + var exception = Assert.Throws(() => serviceProvider.GetService(typeof(IFoo))); + Assert.Equal($"Cannot consume scoped service '{typeof(IBaz)}' from singleton '{typeof(IBar)}'.", exception.Message); + } + + [Fact] + public void GetService_Throws_WhenScopedIsInjectedIntoSingletonThroughSingletonAndScopedWhileInScope() + { + // Arrange + var serviceCollection = new ServiceCollection(); + + serviceCollection.AddScoped(); + serviceCollection.AddSingleton(); + serviceCollection.AddScoped(); + var serviceProvider = serviceCollection.BuildServiceProvider(validateScopes: true); + var scope = serviceProvider.CreateScope(); + + // Act + Assert + var exception = Assert.Throws(() => scope.ServiceProvider.GetService(typeof(IFoo))); + Assert.Equal($"Cannot consume scoped service '{typeof(IBaz)}' from singleton '{typeof(IBar)}'.", exception.Message); + } + + [Fact] + public void GetService_Throws_WhenGetServiceForScopedServiceIsCalledOnRoot() + { + // Arrange + var serviceCollection = new ServiceCollection(); + serviceCollection.AddScoped(); + var serviceProvider = serviceCollection.BuildServiceProvider(validateScopes: true); + + // Act + Assert + var exception = Assert.Throws(() => serviceProvider.GetService(typeof(IBar))); + Assert.Equal($"Cannot resolve scoped service '{typeof(IBar)}' from root provider.", exception.Message); + } + + [Fact] + public void GetService_Throws_WhenGetServiceForScopedServiceIsCalledOnRootViaTransient() + { + // Arrange + var serviceCollection = new ServiceCollection(); + serviceCollection.AddTransient(); + serviceCollection.AddScoped(); + var serviceProvider = serviceCollection.BuildServiceProvider(validateScopes: true); + + // Act + Assert + var exception = Assert.Throws(() => serviceProvider.GetService(typeof(IFoo))); + Assert.Equal($"Cannot resolve '{typeof(IFoo)}' from root provider because it requires scoped service '{typeof(IBar)}'.", exception.Message); + } + + [Fact] + public void GetService_DoesNotThrow_WhenScopeFactoryIsInjectedIntoSingleton() + { + // Arrange + var serviceCollection = new ServiceCollection(); + serviceCollection.AddSingleton(); + var serviceProvider = serviceCollection.BuildServiceProvider(true); + + // Act + Assert + var result = serviceProvider.GetService(typeof(IBoo)); + Assert.NotNull(result); + } + + private interface IFoo + { + } + + private class Foo : IFoo + { + public Foo(IBar bar) + { + } + } + + private interface IBar + { + } + + private class Bar : IBar + { + } + + private class Bar2 : IBar + { + public Bar2(IBaz baz) + { + } + } + + private interface IBaz + { + } + + private class Baz : IBaz + { + } + + private interface IBoo + { + } + + private class Boo : IBoo + { + public Boo(IServiceScopeFactory scopeFactory) + { + } + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceTableTest.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceTableTest.cs new file mode 100644 index 00000000000..3747c4785aa --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/ServiceTableTest.cs @@ -0,0 +1,73 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using Microsoft.AspNetCore.Testing; +using Xunit; + +namespace Microsoft.Extensions.DependencyInjection.ServiceLookup +{ + public class ServiceTableTest + { + [Theory] + [InlineData(typeof(List))] + [InlineData(typeof(string))] + [InlineData(typeof(object))] + public void Constructor_WithImplementationType_ThrowsIfServiceTypeIsOpenGenericAndImplementationTypeIsClosed(Type type) + { + // Arrange + var serviceDescriptors = new[] + { + new ServiceDescriptor(typeof(IList<>), type, ServiceLifetime.Transient) + }; + + // Act and Assert + ExceptionAssert.ThrowsArgument( + () => new CallSiteFactory(serviceDescriptors), + "descriptors", + $"Open generic service type '{typeof(IList<>)}' requires registering an open generic implementation type."); + } + + public static TheoryData Constructor_WithInstance_ThrowsIfServiceTypeIsOpenGenericData => + new TheoryData + { + new List(), + "Hello world", + new object() + }; + + [Theory] + [MemberData(nameof(Constructor_WithInstance_ThrowsIfServiceTypeIsOpenGenericData))] + public void Constructor_WithInstance_ThrowsIfServiceTypeIsOpenGeneric(object instance) + { + // Arrange + var serviceDescriptors = new[] + { + new ServiceDescriptor(typeof(IEnumerable<>), instance) + }; + + // Act and Assert + var ex = ExceptionAssert.ThrowsArgument( + () => new CallSiteFactory(serviceDescriptors), + "descriptors", + $"Open generic service type '{typeof(IEnumerable<>)}' requires registering an open generic implementation type."); + } + + [Fact] + public void Constructor_WithFactory_ThrowsIfServiceTypeIsOpenGeneric() + { + // Arrange + var serviceDescriptors = new[] + { + new ServiceDescriptor(typeof(Tuple<>), _ => new Tuple(1), ServiceLifetime.Transient) + }; + + // Act and Assert + var ex = ExceptionAssert.ThrowsArgument( + () => new CallSiteFactory(serviceDescriptors), + "descriptors", + $"Open generic service type '{typeof(Tuple<>)}' requires registering an open generic implementation type."); + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Utils/MultiServiceHelpers.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Utils/MultiServiceHelpers.cs new file mode 100644 index 00000000000..2cfd6d36784 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/Utils/MultiServiceHelpers.cs @@ -0,0 +1,54 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; + +namespace Microsoft.Extensions.DependencyInjection.Tests +{ + public static class MultiServiceHelpers + { + public static IEnumerable GetMultiService(Type collectionType, Func getAllServices) + { + if (IsGenericIEnumerable(collectionType)) + { + Type serviceType = FirstGenericArgument(collectionType); + return Cast(getAllServices(serviceType), serviceType); + } + + return null; + } + + private static IEnumerable Cast(IEnumerable collection, Type castItemsTo) + { + IList castedCollection = CreateEmptyList(castItemsTo); + + foreach (object item in collection) + { + castedCollection.Add(item); + } + + return castedCollection; + } + + private static bool IsGenericIEnumerable(Type type) + { + return type.GetTypeInfo().IsGenericType && + type.GetGenericTypeDefinition() == typeof(IEnumerable<>); + } + + private static Type FirstGenericArgument(Type type) + { + return type.GetTypeInfo().GenericTypeArguments.Single(); + } + + private static IList CreateEmptyList(Type innerType) + { + Type listType = typeof(List<>).MakeGenericType(innerType); + return (IList)Activator.CreateInstance(listType); + } + } +} diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/xunit.runner.json b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/xunit.runner.json new file mode 100644 index 00000000000..eff47a28bdc --- /dev/null +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/xunit.runner.json @@ -0,0 +1,4 @@ +{ + "methodDisplay": "method", + "appDomain": "denied" +}