Merge branch 'release/2.1' into release/2.2

Commit migrated from https://github.com/dotnet/Extensions/commit/5b8b6c7a52de5bdf5b916c6dddb33e75155389bf
This commit is contained in:
Nate McMaster committed 2018-11-02 01:28:11 -07:00
114 files changed
+14479

No files matched your search

@@ -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
{
/// <summary>
/// Helper code for the various activator services.
/// </summary>
#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<Func<IServiceProvider, Type, Type, bool, object>>((sp, t, r, c) => GetService(sp, t, r, c));
/// <summary>
/// Instantiate a type with constructor arguments provided directly and/or from an <see cref="IServiceProvider"/>.
/// </summary>
/// <param name="provider">The service provider used to resolve dependencies</param>
/// <param name="instanceType">The type to activate</param>
/// <param name="parameters">Constructor arguments not provided by the <paramref name="provider"/>.</param>
/// <returns>An activated object of type instanceType</returns>
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);
}
/// <summary>
/// Create a delegate that will instantiate a type with constructor arguments provided directly
/// and/or from an <see cref="IServiceProvider"/>.
/// </summary>
/// <param name="instanceType">The type to activate</param>
/// <param name="argumentTypes">
/// The types of objects, in order, that will be passed to the returned function as its second parameter
/// </param>
/// <returns>
/// A factory that will instantiate instanceType using an <see cref="IServiceProvider"/>
/// and an argument array containing objects matching the types defined in argumentTypes
/// </returns>
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<Func<IServiceProvider, object[], object>>(
factoryExpressionBody, provider, argumentArray);
var result = factoryLamda.Compile();
return result.Invoke;
}
/// <summary>
/// Instantiate a type with constructor arguments provided directly and/or from an <see cref="IServiceProvider"/>.
/// </summary>
/// <typeparam name="T">The type to activate</typeparam>
/// <param name="provider">The service provider used to resolve dependencies</param>
/// <param name="parameters">Constructor arguments not provided by the <paramref name="provider"/>.</param>
/// <returns>An activated object of type T</returns>
public static T CreateInstance<T>(IServiceProvider provider, params object[] parameters)
{
return (T)CreateInstance(provider, typeof(T), parameters);
}
/// <summary>
/// Retrieve an instance of the given type from the service provider. If one is not found then instantiate it directly.
/// </summary>
/// <typeparam name="T">The type of the service</typeparam>
/// <param name="provider">The service provider used to resolve dependencies</param>
/// <returns>The resolved service or created instance</returns>
public static T GetServiceOrCreateInstance<T>(IServiceProvider provider)
{
return (T)GetServiceOrCreateInstance(provider, typeof(T));
}
/// <summary>
/// Retrieve an instance of the given type from the service provider. If one is not found then instantiate it directly.
/// </summary>
/// <param name="provider">The service provider</param>
/// <param name="type">The type of the service</param>
/// <returns>The resolved service or created instance</returns>
public static object GetServiceOrCreateInstance(IServiceProvider provider, Type type)
{
return provider.GetService(type) ?? CreateInstance(provider, type);
}
private static MethodInfo GetMethodInfo<T>(Expression<T> 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.");
}
}
}
@@ -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
{
/// <summary>
/// Marks the constructor to be used when activating type using <see cref="ActivatorUtilities"/>.
/// </summary>
#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
{
}
}
@@ -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
{
/// <summary>
/// The result of <see cref="ActivatorUtilities.CreateFactory(Type, Type[])"/>.
/// </summary>
/// <param name="serviceProvider">The <see cref="IServiceProvider"/> to get service arguments from.</param>
/// <param name="arguments">Additional constructor arguments.</param>
/// <returns>The instantiated type.</returns>
#if ActivatorUtilities_In_DependencyInjection
public
#else
internal
#endif
delegate object ObjectFactory(IServiceProvider serviceProvider, object[] arguments);
}
@@ -0,0 +1,8 @@
<Project>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)..\ParameterDefaultValue\ParameterDefaultValue.cs">
<Pack>true</Pack>
<PackagePath>$(ContentTargetFolders)\cs\netstandard1.0\</PackagePath>
</Compile>
</ItemGroup>
</Project>
@@ -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;
}
}
}
@@ -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
{
/// <summary>
/// Extension methods for adding and removing services to an <see cref="IServiceCollection" />.
/// </summary>
public static class ServiceCollectionDescriptorExtensions
{
/// <summary>
/// Adds the specified <paramref name="descriptor"/> to the <paramref name="collection"/>.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="descriptor">The <see cref="ServiceDescriptor"/> to add.</param>
/// <returns>A reference to the current instance of <see cref="IServiceCollection"/>.</returns>
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;
}
/// <summary>
/// Adds a sequence of <see cref="ServiceDescriptor"/> to the <paramref name="collection"/>.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="descriptors">The <see cref="ServiceDescriptor"/>s to add.</param>
/// <returns>A reference to the current instance of <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection Add(
this IServiceCollection collection,
IEnumerable<ServiceDescriptor> 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;
}
/// <summary>
/// Adds the specified <paramref name="descriptor"/> to the <paramref name="collection"/> if the
/// service type hasn't already been registered.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="descriptor">The <see cref="ServiceDescriptor"/> to add.</param>
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);
}
}
/// <summary>
/// Adds the specified <paramref name="descriptors"/> to the <paramref name="collection"/> if the
/// service type hasn't already been registered.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="descriptors">The <see cref="ServiceDescriptor"/>s to add.</param>
public static void TryAdd(
this IServiceCollection collection,
IEnumerable<ServiceDescriptor> 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);
}
}
/// <summary>
/// Adds the specified <paramref name="service"/> as a <see cref="ServiceLifetime.Transient"/> service
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="service">The type of the service to register.</param>
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);
}
/// <summary>
/// Adds the specified <paramref name="service"/> as a <see cref="ServiceLifetime.Transient"/> service
/// with the <paramref name="implementationType"/> implementation
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="service">The type of the service to register.</param>
/// <param name="implementationType">The implementation type of the service.</param>
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);
}
/// <summary>
/// Adds the specified <paramref name="service"/> as a <see cref="ServiceLifetime.Transient"/> service
/// using the factory specified in <paramref name="implementationFactory"/>
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="service">The type of the service to register.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
public static void TryAddTransient(
this IServiceCollection collection,
Type service,
Func<IServiceProvider, object> 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);
}
/// <summary>
/// Adds the specified <typeparamref name="TService"/> as a <see cref="ServiceLifetime.Transient"/> service
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
public static void TryAddTransient<TService>(this IServiceCollection collection)
where TService : class
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
TryAddTransient(collection, typeof(TService), typeof(TService));
}
/// <summary>
/// Adds the specified <typeparamref name="TService"/> as a <see cref="ServiceLifetime.Transient"/> service
/// implementation type specified in <typeparamref name="TImplementation"/>
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
public static void TryAddTransient<TService, TImplementation>(this IServiceCollection collection)
where TService : class
where TImplementation : class, TService
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
TryAddTransient(collection, typeof(TService), typeof(TImplementation));
}
/// <summary>
/// Adds the specified <typeparamref name="TService"/> as a <see cref="ServiceLifetime.Transient"/> service
/// using the factory specified in <paramref name="implementationFactory"/>
/// to the <paramref name="services"/> if the service type hasn't already been registered.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
public static void TryAddTransient<TService>(
this IServiceCollection services,
Func<IServiceProvider, TService> implementationFactory)
where TService : class
{
services.TryAdd(ServiceDescriptor.Transient(implementationFactory));
}
/// <summary>
/// Adds the specified <paramref name="service"/> as a <see cref="ServiceLifetime.Scoped"/> service
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="service">The type of the service to register.</param>
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);
}
/// <summary>
/// Adds the specified <paramref name="service"/> as a <see cref="ServiceLifetime.Scoped"/> service
/// with the <paramref name="implementationType"/> implementation
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="service">The type of the service to register.</param>
/// <param name="implementationType">The implementation type of the service.</param>
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);
}
/// <summary>
/// Adds the specified <paramref name="service"/> as a <see cref="ServiceLifetime.Scoped"/> service
/// using the factory specified in <paramref name="implementationFactory"/>
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="service">The type of the service to register.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
public static void TryAddScoped(
this IServiceCollection collection,
Type service,
Func<IServiceProvider, object> 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);
}
/// <summary>
/// Adds the specified <typeparamref name="TService"/> as a <see cref="ServiceLifetime.Scoped"/> service
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
public static void TryAddScoped<TService>(this IServiceCollection collection)
where TService : class
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
TryAddScoped(collection, typeof(TService), typeof(TService));
}
/// <summary>
/// Adds the specified <typeparamref name="TService"/> as a <see cref="ServiceLifetime.Scoped"/> service
/// implementation type specified in <typeparamref name="TImplementation"/>
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
public static void TryAddScoped<TService, TImplementation>(this IServiceCollection collection)
where TService : class
where TImplementation : class, TService
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
TryAddScoped(collection, typeof(TService), typeof(TImplementation));
}
/// <summary>
/// Adds the specified <typeparamref name="TService"/> as a <see cref="ServiceLifetime.Scoped"/> service
/// using the factory specified in <paramref name="implementationFactory"/>
/// to the <paramref name="services"/> if the service type hasn't already been registered.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
public static void TryAddScoped<TService>(
this IServiceCollection services,
Func<IServiceProvider, TService> implementationFactory)
where TService : class
{
services.TryAdd(ServiceDescriptor.Scoped(implementationFactory));
}
/// <summary>
/// Adds the specified <paramref name="service"/> as a <see cref="ServiceLifetime.Singleton"/> service
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="service">The type of the service to register.</param>
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);
}
/// <summary>
/// Adds the specified <paramref name="service"/> as a <see cref="ServiceLifetime.Singleton"/> service
/// with the <paramref name="implementationType"/> implementation
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="service">The type of the service to register.</param>
/// <param name="implementationType">The implementation type of the service.</param>
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);
}
/// <summary>
/// Adds the specified <paramref name="service"/> as a <see cref="ServiceLifetime.Singleton"/> service
/// using the factory specified in <paramref name="implementationFactory"/>
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="service">The type of the service to register.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
public static void TryAddSingleton(
this IServiceCollection collection,
Type service,
Func<IServiceProvider, object> 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);
}
/// <summary>
/// Adds the specified <typeparamref name="TService"/> as a <see cref="ServiceLifetime.Singleton"/> service
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
public static void TryAddSingleton<TService>(this IServiceCollection collection)
where TService : class
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
TryAddSingleton(collection, typeof(TService), typeof(TService));
}
/// <summary>
/// Adds the specified <typeparamref name="TService"/> as a <see cref="ServiceLifetime.Singleton"/> service
/// implementation type specified in <typeparamref name="TImplementation"/>
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
public static void TryAddSingleton<TService, TImplementation>(this IServiceCollection collection)
where TService : class
where TImplementation : class, TService
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
TryAddSingleton(collection, typeof(TService), typeof(TImplementation));
}
/// <summary>
/// Adds the specified <typeparamref name="TService"/> as a <see cref="ServiceLifetime.Singleton"/> service
/// with an instance specified in <paramref name="instance"/>
/// to the <paramref name="collection"/> if the service type hasn't already been registered.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="instance">The instance of the service to add.</param>
public static void TryAddSingleton<TService>(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);
}
/// <summary>
/// Adds the specified <typeparamref name="TService"/> as a <see cref="ServiceLifetime.Singleton"/> service
/// using the factory specified in <paramref name="implementationFactory"/>
/// to the <paramref name="services"/> if the service type hasn't already been registered.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
public static void TryAddSingleton<TService>(
this IServiceCollection services,
Func<IServiceProvider, TService> implementationFactory)
where TService : class
{
services.TryAdd(ServiceDescriptor.Singleton(implementationFactory));
}
/// <summary>
/// Adds a <see cref="ServiceDescriptor"/> if an existing descriptor with the same
/// <see cref="ServiceDescriptor.ServiceType"/> and an implementation that does not already exist
/// in <paramref name="services."/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <param name="descriptor">The <see cref="ServiceDescriptor"/>.</param>
/// <remarks>
/// Use <see cref="TryAddEnumerable(IServiceCollection, ServiceDescriptor)"/> when registing a service implementation of a
/// service type that
/// supports multiple registrations of the same service type. Using
/// <see cref="Add(IServiceCollection, ServiceDescriptor)"/> is not idempotent and can add
/// duplicate
/// <see cref="ServiceDescriptor"/> instances if called twice. Using
/// <see cref="TryAddEnumerable(IServiceCollection, ServiceDescriptor)"/> will prevent registration
/// of multiple implementation types.
/// </remarks>
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);
}
}
/// <summary>
/// Adds the specified <see cref="ServiceDescriptor"/>s if an existing descriptor with the same
/// <see cref="ServiceDescriptor.ServiceType"/> and an implementation that does not already exist
/// in <paramref name="services."/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/>.</param>
/// <param name="descriptors">The <see cref="ServiceDescriptor"/>s.</param>
/// <remarks>
/// Use <see cref="TryAddEnumerable(IServiceCollection, ServiceDescriptor)"/> when registing a service
/// implementation of a service type that
/// supports multiple registrations of the same service type. Using
/// <see cref="Add(IServiceCollection, ServiceDescriptor)"/> is not idempotent and can add
/// duplicate
/// <see cref="ServiceDescriptor"/> instances if called twice. Using
/// <see cref="TryAddEnumerable(IServiceCollection, ServiceDescriptor)"/> will prevent registration
/// of multiple implementation types.
/// </remarks>
public static void TryAddEnumerable(
this IServiceCollection services,
IEnumerable<ServiceDescriptor> 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);
}
}
/// <summary>
/// Removes the first service in <see cref="IServiceCollection"/> with the same service type
/// as <paramref name="descriptor"/> and adds <paramef name="descriptor"/> to the collection.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="descriptor">The <see cref="ServiceDescriptor"/> to replace with.</param>
/// <returns></returns>
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;
}
/// <summary>
/// Removes all services of type <typeparamef name="T"/> in <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <returns></returns>
public static IServiceCollection RemoveAll<T>(this IServiceCollection collection)
{
return RemoveAll(collection, typeof(T));
}
/// <summary>
/// Removes all services of type <paramef name="serviceType"/> in <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="serviceType">The service type to remove.</param>
/// <returns></returns>
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;
}
}
}
@@ -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
{
/// <summary>
/// Specifies the contract for a collection of service descriptors.
/// </summary>
public interface IServiceCollection : IList<ServiceDescriptor>
{
}
}
@@ -0,0 +1,24 @@
using System;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Provides an extension point for creating a container specific builder and an <see cref="IServiceProvider"/>.
/// </summary>
public interface IServiceProviderFactory<TContainerBuilder>
{
/// <summary>
/// Creates a container builder from an <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The collection of services</param>
/// <returns>A container builder that can be used to create an <see cref="IServiceProvider"/>.</returns>
TContainerBuilder CreateBuilder(IServiceCollection services);
/// <summary>
/// Creates an <see cref="IServiceProvider"/> from the container builder.
/// </summary>
/// <param name="containerBuilder">The container builder</param>
/// <returns>An <see cref="IServiceProvider"/></returns>
IServiceProvider CreateServiceProvider(TContainerBuilder containerBuilder);
}
}
@@ -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
{
/// <summary>
/// The <see cref="System.IDisposable.Dispose"/> method ends the scope lifetime. Once Dispose
/// is called, any scoped services that have been resolved from
/// <see cref="Microsoft.Extensions.DependencyInjection.IServiceScope.ServiceProvider"/> will be
/// disposed.
/// </summary>
public interface IServiceScope : IDisposable
{
/// <summary>
/// The <see cref="System.IServiceProvider"/> used to resolve dependencies from the scope.
/// </summary>
IServiceProvider ServiceProvider { get; }
}
}
@@ -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
{
/// <summary>
/// A factory for creating instances of <see cref="IServiceScope"/>, which is used to create
/// services within a scope.
/// </summary>
public interface IServiceScopeFactory
{
/// <summary>
/// Create an <see cref="Microsoft.Extensions.DependencyInjection.IServiceScope"/> which
/// contains an <see cref="System.IServiceProvider"/> used to resolve dependencies from a
/// newly created scope.
/// </summary>
/// <returns>
/// An <see cref="Microsoft.Extensions.DependencyInjection.IServiceScope"/> controlling the
/// lifetime of the scope. Once this is disposed, any scoped services that have been resolved
/// from the <see cref="Microsoft.Extensions.DependencyInjection.IServiceScope.ServiceProvider"/>
/// will also be disposed.
/// </returns>
IServiceScope CreateScope();
}
}
@@ -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
{
/// <summary>
/// Optional contract used by <see cref="ServiceProviderServiceExtensions.GetRequiredService{T}(IServiceProvider)"/>
/// to resolve services if supported by <see cref="IServiceProvider"/>.
/// </summary>
public interface ISupportRequiredService
{
/// <summary>
/// Gets service of type <paramref name="serviceType"/> from the <see cref="IServiceProvider"/> implementing
/// this interface.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>A service object of type <paramref name="serviceType"/>.
/// Throws an exception if the <see cref="IServiceProvider"/> cannot create the object.</returns>
object GetRequiredService(Type serviceType);
}
}
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Description>Abstractions for dependency injection.
Commonly used types:
Microsoft.Extensions.DependencyInjection.IServiceCollection</Description>
<TargetFramework>netstandard2.0</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageTags>dependencyinjection;di</PackageTags>
<DefineConstants>$(DefineConstants);ActivatorUtilities_In_DependencyInjection</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\Shared\src\ParameterDefaultValue\*.cs" />
<Compile Include="..\..\..\Shared\src\ActivatorUtilities\*.cs" />
</ItemGroup>
</Project>
@@ -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")]
@@ -0,0 +1,114 @@
// <auto-generated />
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);
/// <summary>
/// Multiple constructors accepting all given argument types have been found in type '{0}'. There should only be one applicable constructor.
/// </summary>
internal static string AmbiguousConstructorMatch
{
get => GetString("AmbiguousConstructorMatch");
}
/// <summary>
/// Multiple constructors accepting all given argument types have been found in type '{0}'. There should only be one applicable constructor.
/// </summary>
internal static string FormatAmbiguousConstructorMatch(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("AmbiguousConstructorMatch"), p0);
/// <summary>
/// Unable to locate implementation '{0}' for service '{1}'.
/// </summary>
internal static string CannotLocateImplementation
{
get => GetString("CannotLocateImplementation");
}
/// <summary>
/// Unable to locate implementation '{0}' for service '{1}'.
/// </summary>
internal static string FormatCannotLocateImplementation(object p0, object p1)
=> string.Format(CultureInfo.CurrentCulture, GetString("CannotLocateImplementation"), p0, p1);
/// <summary>
/// Unable to resolve service for type '{0}' while attempting to activate '{1}'.
/// </summary>
internal static string CannotResolveService
{
get => GetString("CannotResolveService");
}
/// <summary>
/// Unable to resolve service for type '{0}' while attempting to activate '{1}'.
/// </summary>
internal static string FormatCannotResolveService(object p0, object p1)
=> string.Format(CultureInfo.CurrentCulture, GetString("CannotResolveService"), p0, p1);
/// <summary>
/// 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.
/// </summary>
internal static string NoConstructorMatch
{
get => GetString("NoConstructorMatch");
}
/// <summary>
/// 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.
/// </summary>
internal static string FormatNoConstructorMatch(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("NoConstructorMatch"), p0);
/// <summary>
/// No service for type '{0}' has been registered.
/// </summary>
internal static string NoServiceRegistered
{
get => GetString("NoServiceRegistered");
}
/// <summary>
/// No service for type '{0}' has been registered.
/// </summary>
internal static string FormatNoServiceRegistered(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("NoServiceRegistered"), p0);
/// <summary>
/// Implementation type cannot be '{0}' because it is indistinguishable from other services registered for '{1}'.
/// </summary>
internal static string TryAddIndistinguishableTypeToEnumerable
{
get => GetString("TryAddIndistinguishableTypeToEnumerable");
}
/// <summary>
/// Implementation type cannot be '{0}' because it is indistinguishable from other services registered for '{1}'.
/// </summary>
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;
}
}
}
@@ -0,0 +1,144 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AmbiguousConstructorMatch" xml:space="preserve">
<value>Multiple constructors accepting all given argument types have been found in type '{0}'. There should only be one applicable constructor.</value>
<comment>{0} = service type</comment>
</data>
<data name="CannotLocateImplementation" xml:space="preserve">
<value>Unable to locate implementation '{0}' for service '{1}'.</value>
<comment>{0} = implementation type, {1} = service type</comment>
</data>
<data name="CannotResolveService" xml:space="preserve">
<value>Unable to resolve service for type '{0}' while attempting to activate '{1}'.</value>
<comment>{0} = service which cannot be resolved, {1} = service being activated</comment>
</data>
<data name="NoConstructorMatch" xml:space="preserve">
<value>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.</value>
<comment>{0} = service type</comment>
</data>
<data name="NoServiceRegistered" xml:space="preserve">
<value>No service for type '{0}' has been registered.</value>
<comment>{0} = service type</comment>
</data>
<data name="TryAddIndistinguishableTypeToEnumerable" xml:space="preserve">
<value>Implementation type cannot be '{0}' because it is indistinguishable from other services registered for '{1}'.</value>
<comment>{0} = implementation type, {1} = service type</comment>
</data>
</root>
@@ -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
{
/// <summary>
/// Extension methods for adding services to an <see cref="IServiceCollection" />.
/// </summary>
public static class ServiceCollectionServiceExtensions
{
/// <summary>
/// Adds a transient service of the type specified in <paramref name="serviceType"/> with an
/// implementation of the type specified in <paramref name="implementationType"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationType">The implementation type of the service.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Transient"/>
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);
}
/// <summary>
/// Adds a transient service of the type specified in <paramref name="serviceType"/> with a
/// factory specified in <paramref name="implementationFactory"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Transient"/>
public static IServiceCollection AddTransient(
this IServiceCollection services,
Type serviceType,
Func<IServiceProvider, object> 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);
}
/// <summary>
/// Adds a transient service of the type specified in <typeparamref name="TService"/> with an
/// implementation type specified in <typeparamref name="TImplementation"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Transient"/>
public static IServiceCollection AddTransient<TService, TImplementation>(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));
}
/// <summary>
/// Adds a transient service of the type specified in <paramref name="serviceType"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="serviceType">The type of the service to register and the implementation to use.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Transient"/>
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);
}
/// <summary>
/// Adds a transient service of the type specified in <typeparamref name="TService"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Transient"/>
public static IServiceCollection AddTransient<TService>(this IServiceCollection services)
where TService : class
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
return services.AddTransient(typeof(TService));
}
/// <summary>
/// Adds a transient service of the type specified in <typeparamref name="TService"/> with a
/// factory specified in <paramref name="implementationFactory"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Transient"/>
public static IServiceCollection AddTransient<TService>(
this IServiceCollection services,
Func<IServiceProvider, TService> 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);
}
/// <summary>
/// Adds a transient service of the type specified in <typeparamref name="TService"/> with an
/// implementation type specified in <typeparamref name="TImplementation" /> using the
/// factory specified in <paramref name="implementationFactory"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Transient"/>
public static IServiceCollection AddTransient<TService, TImplementation>(
this IServiceCollection services,
Func<IServiceProvider, TImplementation> 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);
}
/// <summary>
/// Adds a scoped service of the type specified in <paramref name="serviceType"/> with an
/// implementation of the type specified in <paramref name="implementationType"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationType">The implementation type of the service.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Scoped"/>
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);
}
/// <summary>
/// Adds a scoped service of the type specified in <paramref name="serviceType"/> with a
/// factory specified in <paramref name="implementationFactory"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Scoped"/>
public static IServiceCollection AddScoped(
this IServiceCollection services,
Type serviceType,
Func<IServiceProvider, object> 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);
}
/// <summary>
/// Adds a scoped service of the type specified in <typeparamref name="TService"/> with an
/// implementation type specified in <typeparamref name="TImplementation"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Scoped"/>
public static IServiceCollection AddScoped<TService, TImplementation>(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));
}
/// <summary>
/// Adds a scoped service of the type specified in <paramref name="serviceType"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="serviceType">The type of the service to register and the implementation to use.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Scoped"/>
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);
}
/// <summary>
/// Adds a scoped service of the type specified in <typeparamref name="TService"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Scoped"/>
public static IServiceCollection AddScoped<TService>(this IServiceCollection services)
where TService : class
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
return services.AddScoped(typeof(TService));
}
/// <summary>
/// Adds a scoped service of the type specified in <typeparamref name="TService"/> with a
/// factory specified in <paramref name="implementationFactory"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Scoped"/>
public static IServiceCollection AddScoped<TService>(
this IServiceCollection services,
Func<IServiceProvider, TService> 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);
}
/// <summary>
/// Adds a scoped service of the type specified in <typeparamref name="TService"/> with an
/// implementation type specified in <typeparamref name="TImplementation" /> using the
/// factory specified in <paramref name="implementationFactory"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Scoped"/>
public static IServiceCollection AddScoped<TService, TImplementation>(
this IServiceCollection services,
Func<IServiceProvider, TImplementation> 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);
}
/// <summary>
/// Adds a singleton service of the type specified in <paramref name="serviceType"/> with an
/// implementation of the type specified in <paramref name="implementationType"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationType">The implementation type of the service.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton"/>
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);
}
/// <summary>
/// Adds a singleton service of the type specified in <paramref name="serviceType"/> with a
/// factory specified in <paramref name="implementationFactory"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton"/>
public static IServiceCollection AddSingleton(
this IServiceCollection services,
Type serviceType,
Func<IServiceProvider, object> 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);
}
/// <summary>
/// Adds a singleton service of the type specified in <typeparamref name="TService"/> with an
/// implementation type specified in <typeparamref name="TImplementation"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton"/>
public static IServiceCollection AddSingleton<TService, TImplementation>(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));
}
/// <summary>
/// Adds a singleton service of the type specified in <paramref name="serviceType"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="serviceType">The type of the service to register and the implementation to use.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton"/>
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);
}
/// <summary>
/// Adds a singleton service of the type specified in <typeparamref name="TService"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton"/>
public static IServiceCollection AddSingleton<TService>(this IServiceCollection services)
where TService : class
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
return services.AddSingleton(typeof(TService));
}
/// <summary>
/// Adds a singleton service of the type specified in <typeparamref name="TService"/> with a
/// factory specified in <paramref name="implementationFactory"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton"/>
public static IServiceCollection AddSingleton<TService>(
this IServiceCollection services,
Func<IServiceProvider, TService> 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);
}
/// <summary>
/// Adds a singleton service of the type specified in <typeparamref name="TService"/> with an
/// implementation type specified in <typeparamref name="TImplementation" /> using the
/// factory specified in <paramref name="implementationFactory"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="implementationFactory">The factory that creates the service.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton"/>
public static IServiceCollection AddSingleton<TService, TImplementation>(
this IServiceCollection services,
Func<IServiceProvider, TImplementation> 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);
}
/// <summary>
/// Adds a singleton service of the type specified in <paramref name="serviceType"/> with an
/// instance specified in <paramref name="implementationInstance"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="serviceType">The type of the service to register.</param>
/// <param name="implementationInstance">The instance of the service.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton"/>
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;
}
/// <summary>
/// Adds a singleton service of the type specified in <typeparamref name="TService" /> with an
/// instance specified in <paramref name="implementationInstance"/> to the
/// specified <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <param name="implementationInstance">The instance of the service.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ServiceLifetime.Singleton"/>
public static IServiceCollection AddSingleton<TService>(
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<IServiceProvider, object> implementationFactory,
ServiceLifetime lifetime)
{
var descriptor = new ServiceDescriptor(serviceType, implementationFactory, lifetime);
collection.Add(descriptor);
return collection;
}
}
}
@@ -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
{
/// <summary>
/// Describes a service with its service type, implementation, and lifetime.
/// </summary>
[DebuggerDisplay("Lifetime = {Lifetime}, ServiceType = {ServiceType}, ImplementationType = {ImplementationType}")]
public class ServiceDescriptor
{
/// <summary>
/// Initializes a new instance of <see cref="ServiceDescriptor"/> with the specified <paramref name="implementationType"/>.
/// </summary>
/// <param name="serviceType">The <see cref="Type"/> of the service.</param>
/// <param name="implementationType">The <see cref="Type"/> implementing the service.</param>
/// <param name="lifetime">The <see cref="ServiceLifetime"/> of the service.</param>
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;
}
/// <summary>
/// Initializes a new instance of <see cref="ServiceDescriptor"/> with the specified <paramref name="instance"/>
/// as a <see cref="ServiceLifetime.Singleton"/>.
/// </summary>
/// <param name="serviceType">The <see cref="Type"/> of the service.</param>
/// <param name="instance">The instance implementing the service.</param>
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;
}
/// <summary>
/// Initializes a new instance of <see cref="ServiceDescriptor"/> with the specified <paramref name="factory"/>.
/// </summary>
/// <param name="serviceType">The <see cref="Type"/> of the service.</param>
/// <param name="factory">A factory used for creating service instances.</param>
/// <param name="lifetime">The <see cref="ServiceLifetime"/> of the service.</param>
public ServiceDescriptor(
Type serviceType,
Func<IServiceProvider, object> 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;
}
/// <inheritdoc />
public ServiceLifetime Lifetime { get; }
/// <inheritdoc />
public Type ServiceType { get; }
/// <inheritdoc />
public Type ImplementationType { get; }
/// <inheritdoc />
public object ImplementationInstance { get; }
/// <inheritdoc />
public Func<IServiceProvider, object> 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;
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <typeparamref name="TService"/>, <typeparamref name="TImplementation"/>,
/// and the <see cref="ServiceLifetime.Transient"/> lifetime.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation.</typeparam>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Transient<TService, TImplementation>()
where TService : class
where TImplementation : class, TService
{
return Describe<TService, TImplementation>(ServiceLifetime.Transient);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <paramref name="service"/> and <paramref name="implementationType"/>
/// and the <see cref="ServiceLifetime.Transient"/> lifetime.
/// </summary>
/// <param name="service">The type of the service.</param>
/// <param name="implementationType">The type of the implementation.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
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);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <typeparamref name="TService"/>, <typeparamref name="TImplementation"/>,
/// <paramref name="implementationFactory"/>,
/// and the <see cref="ServiceLifetime.Transient"/> lifetime.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation.</typeparam>
/// <param name="implementationFactory">A factory to create new instances of the service implementation.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Transient<TService, TImplementation>(
Func<IServiceProvider, TImplementation> implementationFactory)
where TService : class
where TImplementation : class, TService
{
if (implementationFactory == null)
{
throw new ArgumentNullException(nameof(implementationFactory));
}
return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <typeparamref name="TService"/>, <paramref name="implementationFactory"/>,
/// and the <see cref="ServiceLifetime.Transient"/> lifetime.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="implementationFactory">A factory to create new instances of the service implementation.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Transient<TService>(Func<IServiceProvider, TService> implementationFactory)
where TService : class
{
if (implementationFactory == null)
{
throw new ArgumentNullException(nameof(implementationFactory));
}
return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <paramref name="service"/>, <paramref name="implementationFactory"/>,
/// and the <see cref="ServiceLifetime.Transient"/> lifetime.
/// </summary>
/// <param name="service">The type of the service.</param>
/// <param name="implementationFactory">A factory to create new instances of the service implementation.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Transient(Type service, Func<IServiceProvider, object> implementationFactory)
{
if (service == null)
{
throw new ArgumentNullException(nameof(service));
}
if (implementationFactory == null)
{
throw new ArgumentNullException(nameof(implementationFactory));
}
return Describe(service, implementationFactory, ServiceLifetime.Transient);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <typeparamref name="TService"/>, <typeparamref name="TImplementation"/>,
/// and the <see cref="ServiceLifetime.Scoped"/> lifetime.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation.</typeparam>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Scoped<TService, TImplementation>()
where TService : class
where TImplementation : class, TService
{
return Describe<TService, TImplementation>(ServiceLifetime.Scoped);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <paramref name="service"/> and <paramref name="implementationType"/>
/// and the <see cref="ServiceLifetime.Scoped"/> lifetime.
/// </summary>
/// <param name="service">The type of the service.</param>
/// <param name="implementationType">The type of the implementation.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Scoped(Type service, Type implementationType)
{
return Describe(service, implementationType, ServiceLifetime.Scoped);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <typeparamref name="TService"/>, <typeparamref name="TImplementation"/>,
/// <paramref name="implementationFactory"/>,
/// and the <see cref="ServiceLifetime.Scoped"/> lifetime.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation.</typeparam>
/// <param name="implementationFactory">A factory to create new instances of the service implementation.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Scoped<TService, TImplementation>(
Func<IServiceProvider, TImplementation> implementationFactory)
where TService : class
where TImplementation : class, TService
{
if (implementationFactory == null)
{
throw new ArgumentNullException(nameof(implementationFactory));
}
return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <typeparamref name="TService"/>, <paramref name="implementationFactory"/>,
/// and the <see cref="ServiceLifetime.Scoped"/> lifetime.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="implementationFactory">A factory to create new instances of the service implementation.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Scoped<TService>(Func<IServiceProvider, TService> implementationFactory)
where TService : class
{
if (implementationFactory == null)
{
throw new ArgumentNullException(nameof(implementationFactory));
}
return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <paramref name="service"/>, <paramref name="implementationFactory"/>,
/// and the <see cref="ServiceLifetime.Scoped"/> lifetime.
/// </summary>
/// <param name="service">The type of the service.</param>
/// <param name="implementationFactory">A factory to create new instances of the service implementation.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Scoped(Type service, Func<IServiceProvider, object> implementationFactory)
{
if (service == null)
{
throw new ArgumentNullException(nameof(service));
}
if (implementationFactory == null)
{
throw new ArgumentNullException(nameof(implementationFactory));
}
return Describe(service, implementationFactory, ServiceLifetime.Scoped);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <typeparamref name="TService"/>, <typeparamref name="TImplementation"/>,
/// and the <see cref="ServiceLifetime.Singleton"/> lifetime.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation.</typeparam>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Singleton<TService, TImplementation>()
where TService : class
where TImplementation : class, TService
{
return Describe<TService, TImplementation>(ServiceLifetime.Singleton);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <paramref name="service"/> and <paramref name="implementationType"/>
/// and the <see cref="ServiceLifetime.Singleton"/> lifetime.
/// </summary>
/// <param name="service">The type of the service.</param>
/// <param name="implementationType">The type of the implementation.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
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);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <typeparamref name="TService"/>, <typeparamref name="TImplementation"/>,
/// <paramref name="implementationFactory"/>,
/// and the <see cref="ServiceLifetime.Singleton"/> lifetime.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation.</typeparam>
/// <param name="implementationFactory">A factory to create new instances of the service implementation.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Singleton<TService, TImplementation>(
Func<IServiceProvider, TImplementation> implementationFactory)
where TService : class
where TImplementation : class, TService
{
if (implementationFactory == null)
{
throw new ArgumentNullException(nameof(implementationFactory));
}
return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <typeparamref name="TService"/>, <paramref name="implementationFactory"/>,
/// and the <see cref="ServiceLifetime.Singleton"/> lifetime.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="implementationFactory">A factory to create new instances of the service implementation.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Singleton<TService>(Func<IServiceProvider, TService> implementationFactory)
where TService : class
{
if (implementationFactory == null)
{
throw new ArgumentNullException(nameof(implementationFactory));
}
return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <paramref name="serviceType"/>, <paramref name="implementationFactory"/>,
/// and the <see cref="ServiceLifetime.Singleton"/> lifetime.
/// </summary>
/// <param name="serviceType">The type of the service.</param>
/// <param name="implementationFactory">A factory to create new instances of the service implementation.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Singleton(
Type serviceType,
Func<IServiceProvider, object> implementationFactory)
{
if (serviceType == null)
{
throw new ArgumentNullException(nameof(serviceType));
}
if (implementationFactory == null)
{
throw new ArgumentNullException(nameof(implementationFactory));
}
return Describe(serviceType, implementationFactory, ServiceLifetime.Singleton);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <typeparamref name="TService"/>, <paramref name="implementationInstance"/>,
/// and the <see cref="ServiceLifetime.Scoped"/> lifetime.
/// </summary>
/// <typeparam name="TService">The type of the service.</typeparam>
/// <param name="implementationInstance">The instance of the implementation.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Singleton<TService>(TService implementationInstance)
where TService : class
{
if (implementationInstance == null)
{
throw new ArgumentNullException(nameof(implementationInstance));
}
return Singleton(typeof(TService), implementationInstance);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <paramref name="serviceType"/>, <paramref name="implementationInstance"/>,
/// and the <see cref="ServiceLifetime.Scoped"/> lifetime.
/// </summary>
/// <param name="serviceType">The type of the service.</param>
/// <param name="implementationInstance">The instance of the implementation.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
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<TService, TImplementation>(ServiceLifetime lifetime)
where TService : class
where TImplementation : class, TService
{
return Describe(
typeof(TService),
typeof(TImplementation),
lifetime: lifetime);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <paramref name="serviceType"/>, <paramref name="implementationType"/>,
/// and <paramref name="lifetime"/>.
/// </summary>
/// <param name="serviceType">The type of the service.</param>
/// <param name="implementationType">The type of the implementation.</param>
/// <param name="lifetime">The lifetime of the service.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Describe(Type serviceType, Type implementationType, ServiceLifetime lifetime)
{
return new ServiceDescriptor(serviceType, implementationType, lifetime);
}
/// <summary>
/// Creates an instance of <see cref="ServiceDescriptor"/> with the specified
/// <paramref name="serviceType"/>, <paramref name="implementationFactory"/>,
/// and <paramref name="lifetime"/>.
/// </summary>
/// <param name="serviceType">The type of the service.</param>
/// <param name="implementationFactory">A factory to create new instances of the service implementation.</param>
/// <param name="lifetime">The lifetime of the service.</param>
/// <returns>A new instance of <see cref="ServiceDescriptor"/>.</returns>
public static ServiceDescriptor Describe(Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime)
{
return new ServiceDescriptor(serviceType, implementationFactory, lifetime);
}
}
}
@@ -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
{
/// <summary>
/// Specifies the lifetime of a service in an <see cref="IServiceCollection"/>.
/// </summary>
public enum ServiceLifetime
{
/// <summary>
/// Specifies that a single instance of the service will be created.
/// </summary>
Singleton,
/// <summary>
/// Specifies that a new instance of the service will be created for each scope.
/// </summary>
/// <remarks>
/// In ASP.NET Core applications a scope is created around each server request.
/// </remarks>
Scoped,
/// <summary>
/// Specifies that a new instance of the service will be created every time it is requested.
/// </summary>
Transient
}
}
@@ -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
{
/// <summary>
/// Extension methods for getting services from an <see cref="IServiceProvider" />.
/// </summary>
public static class ServiceProviderServiceExtensions
{
/// <summary>
/// Get service of type <typeparamref name="T"/> from the <see cref="IServiceProvider"/>.
/// </summary>
/// <typeparam name="T">The type of service object to get.</typeparam>
/// <param name="provider">The <see cref="IServiceProvider"/> to retrieve the service object from.</param>
/// <returns>A service object of type <typeparamref name="T"/> or null if there is no such service.</returns>
public static T GetService<T>(this IServiceProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException(nameof(provider));
}
return (T)provider.GetService(typeof(T));
}
/// <summary>
/// Get service of type <paramref name="serviceType"/> from the <see cref="IServiceProvider"/>.
/// </summary>
/// <param name="provider">The <see cref="IServiceProvider"/> to retrieve the service object from.</param>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>A service object of type <paramref name="serviceType"/>.</returns>
/// <exception cref="System.InvalidOperationException">There is no service of type <paramref name="serviceType"/>.</exception>
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;
}
/// <summary>
/// Get service of type <typeparamref name="T"/> from the <see cref="IServiceProvider"/>.
/// </summary>
/// <typeparam name="T">The type of service object to get.</typeparam>
/// <param name="provider">The <see cref="IServiceProvider"/> to retrieve the service object from.</param>
/// <returns>A service object of type <typeparamref name="T"/>.</returns>
/// <exception cref="System.InvalidOperationException">There is no service of type <typeparamref name="T"/>.</exception>
public static T GetRequiredService<T>(this IServiceProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException(nameof(provider));
}
return (T)provider.GetRequiredService(typeof(T));
}
/// <summary>
/// Get an enumeration of services of type <typeparamref name="T"/> from the <see cref="IServiceProvider"/>.
/// </summary>
/// <typeparam name="T">The type of service object to get.</typeparam>
/// <param name="provider">The <see cref="IServiceProvider"/> to retrieve the services from.</param>
/// <returns>An enumeration of services of type <typeparamref name="T"/>.</returns>
public static IEnumerable<T> GetServices<T>(this IServiceProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException(nameof(provider));
}
return provider.GetRequiredService<IEnumerable<T>>();
}
/// <summary>
/// Get an enumeration of services of type <paramref name="serviceType"/> from the <see cref="IServiceProvider"/>.
/// </summary>
/// <param name="provider">The <see cref="IServiceProvider"/> to retrieve the services from.</param>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>An enumeration of services of type <paramref name="serviceType"/>.</returns>
public static IEnumerable<object> 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<object>)provider.GetRequiredService(genericEnumerable);
}
/// <summary>
/// Creates a new <see cref="IServiceScope"/> that can be used to resolve scoped services.
/// </summary>
/// <param name="provider">The <see cref="IServiceProvider"/> to create the scope from.</param>
/// <returns>A <see cref="IServiceScope"/> that can be used to resolve scoped services.</returns>
public static IServiceScope CreateScope(this IServiceProvider provider)
{
return provider.GetRequiredService<IServiceScopeFactory>().CreateScope();
}
}
}
@@ -0,0 +1,49 @@
using System;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Default implementation of <see cref="IServiceProviderFactory{TContainerBuilder}"/>.
/// </summary>
public class DefaultServiceProviderFactory : IServiceProviderFactory<IServiceCollection>
{
private readonly ServiceProviderOptions _options;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultServiceProviderFactory"/> class
/// with default options.
/// </summary>
/// <seealso cref="ServiceProviderOptions.Default"/>
public DefaultServiceProviderFactory() : this(ServiceProviderOptions.Default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DefaultServiceProviderFactory"/> class
/// with the specified <paramref name="options"/>.
/// </summary>
/// <param name="options">The options to use for this instance.</param>
public DefaultServiceProviderFactory(ServiceProviderOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
_options = options;
}
/// <inheritdoc />
public IServiceCollection CreateBuilder(IServiceCollection services)
{
return services;
}
/// <inheritdoc />
public IServiceProvider CreateServiceProvider(IServiceCollection containerBuilder)
{
return containerBuilder.BuildServiceProvider(_options);
}
}
}
@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Description>Default implementation of dependency injection for Microsoft.Extensions.DependencyInjection.</Description>
<TargetFrameworks>netcoreapp2.0;net461;netstandard2.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageTags>dependencyinjection;di</PackageTags>
<ILEmitBackend Condition="$(TargetFramework) != 'netstandard2.0'">True</ILEmitBackend>
<DefineConstants Condition="'$(ILEmitBackend)' == 'True'">$(DefineConstants);IL_EMIT</DefineConstants>
<!-- Debug IL generation -->
<ILEmitBackendSaveAssemblies>False</ILEmitBackendSaveAssemblies>
<DefineConstants Condition="'$(ILEmitBackendSaveAssemblies)' == 'True'">$(DefineConstants);SAVE_ASSEMBLIES</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
</ItemGroup>
<ItemGroup>
<Compile Remove="ServiceLookup\ILEmit\**\*.cs" />
<Compile Condition="'$(ILEmitBackend)' == 'True'" Include="ServiceLookup\ILEmit\*.cs" />
<Compile Include="..\..\..\Shared\src\ParameterDefaultValue\*.cs" />
<Compile Include="..\..\..\Shared\src\TypeNameHelper\*.cs" />
</ItemGroup>
</Project>
@@ -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")]
@@ -0,0 +1,170 @@
// <auto-generated />
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);
/// <summary>
/// Unable to activate type '{0}'. The following constructors are ambiguous:
/// </summary>
internal static string AmbiguousConstructorException
{
get => GetString("AmbiguousConstructorException");
}
/// <summary>
/// Unable to activate type '{0}'. The following constructors are ambiguous:
/// </summary>
internal static string FormatAmbiguousConstructorException(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("AmbiguousConstructorException"), p0);
/// <summary>
/// Unable to resolve service for type '{0}' while attempting to activate '{1}'.
/// </summary>
internal static string CannotResolveService
{
get => GetString("CannotResolveService");
}
/// <summary>
/// Unable to resolve service for type '{0}' while attempting to activate '{1}'.
/// </summary>
internal static string FormatCannotResolveService(object p0, object p1)
=> string.Format(CultureInfo.CurrentCulture, GetString("CannotResolveService"), p0, p1);
/// <summary>
/// A circular dependency was detected for the service of type '{0}'.
/// </summary>
internal static string CircularDependencyException
{
get => GetString("CircularDependencyException");
}
/// <summary>
/// A circular dependency was detected for the service of type '{0}'.
/// </summary>
internal static string FormatCircularDependencyException(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("CircularDependencyException"), p0);
/// <summary>
/// No constructor for type '{0}' can be instantiated using services from the service container and default values.
/// </summary>
internal static string UnableToActivateTypeException
{
get => GetString("UnableToActivateTypeException");
}
/// <summary>
/// No constructor for type '{0}' can be instantiated using services from the service container and default values.
/// </summary>
internal static string FormatUnableToActivateTypeException(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("UnableToActivateTypeException"), p0);
/// <summary>
/// Open generic service type '{0}' requires registering an open generic implementation type.
/// </summary>
internal static string OpenGenericServiceRequiresOpenGenericImplementation
{
get => GetString("OpenGenericServiceRequiresOpenGenericImplementation");
}
/// <summary>
/// Open generic service type '{0}' requires registering an open generic implementation type.
/// </summary>
internal static string FormatOpenGenericServiceRequiresOpenGenericImplementation(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("OpenGenericServiceRequiresOpenGenericImplementation"), p0);
/// <summary>
/// Cannot instantiate implementation type '{0}' for service type '{1}'.
/// </summary>
internal static string TypeCannotBeActivated
{
get => GetString("TypeCannotBeActivated");
}
/// <summary>
/// Cannot instantiate implementation type '{0}' for service type '{1}'.
/// </summary>
internal static string FormatTypeCannotBeActivated(object p0, object p1)
=> string.Format(CultureInfo.CurrentCulture, GetString("TypeCannotBeActivated"), p0, p1);
/// <summary>
/// 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.
/// </summary>
internal static string NoConstructorMatch
{
get => GetString("NoConstructorMatch");
}
/// <summary>
/// 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.
/// </summary>
internal static string FormatNoConstructorMatch(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("NoConstructorMatch"), p0);
/// <summary>
/// Cannot consume {2} service '{0}' from {3} '{1}'.
/// </summary>
internal static string ScopedInSingletonException
{
get => GetString("ScopedInSingletonException");
}
/// <summary>
/// Cannot consume {2} service '{0}' from {3} '{1}'.
/// </summary>
internal static string FormatScopedInSingletonException(object p0, object p1, object p2, object p3)
=> string.Format(CultureInfo.CurrentCulture, GetString("ScopedInSingletonException"), p0, p1, p2, p3);
/// <summary>
/// Cannot resolve '{0}' from root provider because it requires {2} service '{1}'.
/// </summary>
internal static string ScopedResolvedFromRootException
{
get => GetString("ScopedResolvedFromRootException");
}
/// <summary>
/// Cannot resolve '{0}' from root provider because it requires {2} service '{1}'.
/// </summary>
internal static string FormatScopedResolvedFromRootException(object p0, object p1, object p2)
=> string.Format(CultureInfo.CurrentCulture, GetString("ScopedResolvedFromRootException"), p0, p1, p2);
/// <summary>
/// Cannot resolve {1} service '{0}' from root provider.
/// </summary>
internal static string DirectScopedResolvedFromRootException
{
get => GetString("DirectScopedResolvedFromRootException");
}
/// <summary>
/// Cannot resolve {1} service '{0}' from root provider.
/// </summary>
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;
}
}
}
@@ -0,0 +1,153 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AmbiguousConstructorException" xml:space="preserve">
<value>Unable to activate type '{0}'. The following constructors are ambiguous:</value>
</data>
<data name="CannotResolveService" xml:space="preserve">
<value>Unable to resolve service for type '{0}' while attempting to activate '{1}'.</value>
<comment>{0} = service which cannot be resolved, {1} = service being activated</comment>
</data>
<data name="CircularDependencyException" xml:space="preserve">
<value>A circular dependency was detected for the service of type '{0}'.</value>
<comment>{0} = service type with circular dependency</comment>
</data>
<data name="UnableToActivateTypeException" xml:space="preserve">
<value>No constructor for type '{0}' can be instantiated using services from the service container and default values.</value>
</data>
<data name="OpenGenericServiceRequiresOpenGenericImplementation" xml:space="preserve">
<value>Open generic service type '{0}' requires registering an open generic implementation type.</value>
</data>
<data name="TypeCannotBeActivated" xml:space="preserve">
<value>Cannot instantiate implementation type '{0}' for service type '{1}'.</value>
</data>
<data name="NoConstructorMatch" xml:space="preserve">
<value>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.</value>
<comment>{0} = service type</comment>
</data>
<data name="ScopedInSingletonException" xml:space="preserve">
<value>Cannot consume {2} service '{0}' from {3} '{1}'.</value>
</data>
<data name="ScopedResolvedFromRootException" xml:space="preserve">
<value>Cannot resolve '{0}' from root provider because it requires {2} service '{1}'.</value>
</data>
<data name="DirectScopedResolvedFromRootException" xml:space="preserve">
<value>Cannot resolve {1} service '{0}' from root provider.</value>
</data>
</root>
@@ -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
{
/// <summary>
/// Default implementation of <see cref="IServiceCollection"/>.
/// </summary>
public class ServiceCollection : IServiceCollection
{
private readonly List<ServiceDescriptor> _descriptors = new List<ServiceDescriptor>();
/// <inheritdoc />
public int Count => _descriptors.Count;
/// <inheritdoc />
public bool IsReadOnly => false;
/// <inheritdoc />
public ServiceDescriptor this[int index]
{
get
{
return _descriptors[index];
}
set
{
_descriptors[index] = value;
}
}
/// <inheritdoc />
public void Clear()
{
_descriptors.Clear();
}
/// <inheritdoc />
public bool Contains(ServiceDescriptor item)
{
return _descriptors.Contains(item);
}
/// <inheritdoc />
public void CopyTo(ServiceDescriptor[] array, int arrayIndex)
{
_descriptors.CopyTo(array, arrayIndex);
}
/// <inheritdoc />
public bool Remove(ServiceDescriptor item)
{
return _descriptors.Remove(item);
}
/// <inheritdoc />
public IEnumerator<ServiceDescriptor> GetEnumerator()
{
return _descriptors.GetEnumerator();
}
void ICollection<ServiceDescriptor>.Add(ServiceDescriptor item)
{
_descriptors.Add(item);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <inheritdoc />
public int IndexOf(ServiceDescriptor item)
{
return _descriptors.IndexOf(item);
}
/// <inheritdoc />
public void Insert(int index, ServiceDescriptor item)
{
_descriptors.Insert(index, item);
}
/// <inheritdoc />
public void RemoveAt(int index)
{
_descriptors.RemoveAt(index);
}
}
}
@@ -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
{
/// <summary>
/// Extension methods for building a <see cref="ServiceProvider"/> from an <see cref="IServiceCollection"/>.
/// </summary>
public static class ServiceCollectionContainerBuilderExtensions
{
/// <summary>
/// Creates a <see cref="ServiceProvider"/> containing services from the provided <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> containing service descriptors.</param>
/// <returns>The <see cref="ServiceProvider"/>.</returns>
public static ServiceProvider BuildServiceProvider(this IServiceCollection services)
{
return BuildServiceProvider(services, ServiceProviderOptions.Default);
}
/// <summary>
/// Creates a <see cref="ServiceProvider"/> containing services from the provided <see cref="IServiceCollection"/>
/// optionaly enabling scope validation.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> containing service descriptors.</param>
/// <param name="validateScopes">
/// <c>true</c> to perform check verifying that scoped services never gets resolved from root provider; otherwise <c>false</c>.
/// </param>
/// <returns>The <see cref="ServiceProvider"/>.</returns>
public static ServiceProvider BuildServiceProvider(this IServiceCollection services, bool validateScopes)
{
return services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = validateScopes });
}
/// <summary>
/// Creates a <see cref="ServiceProvider"/> containing services from the provided <see cref="IServiceCollection"/>
/// optionaly enabling scope validation.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> containing service descriptors.</param>
/// <param name="options">
/// Configures various service provider behaviors.
/// </param>
/// <returns>The <see cref="ServiceProvider"/>.</returns>
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);
}
}
}
@@ -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<Type,ChainItemInfo> _callSiteChain;
public CallSiteChain()
{
_callSiteChain = new Dictionary<Type, ChainItemInfo>();
}
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;
}
}
}
}
@@ -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; }
}
}
@@ -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<ServiceDescriptor> _descriptors;
private readonly Dictionary<Type, IServiceCallSite> _callSiteCache = new Dictionary<Type, IServiceCallSite>();
private readonly Dictionary<Type, ServiceDescriptorCacheItem> _descriptorLookup = new Dictionary<Type, ServiceDescriptorCacheItem>();
public CallSiteFactory(IEnumerable<ServiceDescriptor> descriptors)
{
_descriptors = descriptors.ToList();
Populate(descriptors);
}
private void Populate(IEnumerable<ServiceDescriptor> 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<IServiceCallSite>();
// 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<Type> 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<Type>(
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<ServiceDescriptor> _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<ServiceDescriptor>();
newCacheItem._items.Add(descriptor);
}
return newCacheItem;
}
}
}
}
@@ -0,0 +1,25 @@
namespace Microsoft.Extensions.DependencyInjection.ServiceLookup
{
internal enum CallSiteKind
{
Factory,
Constructor,
Constant,
IEnumerable,
ServiceProvider,
Scope,
Transient,
CreateInstance,
ServiceScopeFactory,
Singleton
}
}
@@ -0,0 +1,106 @@
using System;
using System.Runtime.ExceptionServices;
namespace Microsoft.Extensions.DependencyInjection.ServiceLookup
{
internal class CallSiteRuntimeResolver : CallSiteVisitor<ServiceProviderEngineScope, object>
{
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);
}
}
}
@@ -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<CallSiteValidator.CallSiteValidatorState, Type>
{
// Keys are services being resolved via GetService, values - first scoped service in their call site tree
private readonly ConcurrentDictionary<Type, Type> _scopedServices = new ConcurrentDictionary<Type, Type>();
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; }
}
}
}
@@ -0,0 +1,56 @@
using System;
namespace Microsoft.Extensions.DependencyInjection.ServiceLookup
{
internal abstract class CallSiteVisitor<TArgument, TResult>
{
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);
}
}
@@ -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<ServiceDescriptor> serviceDescriptors, IServiceProviderEngineCallback callback) : base(serviceDescriptors, callback)
{
ExpressionResolverBuilder = new ExpressionResolverBuilder(RuntimeResolver, this, Root);
}
protected override Func<ServiceProviderEngineScope, object> RealizeService(IServiceCallSite callSite)
{
var realizedService = ExpressionResolverBuilder.Build(callSite);
RealizedServices[callSite.ServiceType] = realizedService;
return realizedService;
}
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
}
@@ -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<ServiceDescriptor> serviceDescriptors, IServiceProviderEngineCallback callback) : base(serviceDescriptors, callback)
{
}
protected override Func<ServiceProviderEngineScope, object> RealizeService(IServiceCallSite callSite)
{
var callCount = 0;
return scope =>
{
if (Interlocked.Increment(ref callCount) == 2)
{
Task.Run(() => base.RealizeService(callSite));
}
return RuntimeResolver.Resolve(callSite, scope);
};
}
}
}
@@ -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<CallSiteExpressionBuilderContext, Expression>
{
internal static readonly MethodInfo InvokeFactoryMethodInfo = GetMethodInfo<Action<Func<IServiceProvider, object>, IServiceProvider>>((a, b) => a.Invoke(b));
internal static readonly MethodInfo CaptureDisposableMethodInfo = GetMethodInfo<Func<ServiceProviderEngineScope, object, object>>((a, b) => a.CaptureDisposable(b));
internal static readonly MethodInfo TryGetValueMethodInfo = GetMethodInfo<Func<IDictionary<object, object>, object, object, bool>>((a, b, c) => a.TryGetValue(b, out c));
internal static readonly MethodInfo AddMethodInfo = GetMethodInfo<Action<IDictionary<object, object>, object, object>>((a, b, c) => a.Add(b, c));
internal static readonly MethodInfo MonitorEnterMethodInfo = GetMethodInfo<Action<object, bool>>((lockObj, lockTaken) => Monitor.Enter(lockObj, ref lockTaken));
internal static readonly MethodInfo MonitorExitMethodInfo = GetMethodInfo<Action<object>>(lockObj => Monitor.Exit(lockObj));
internal static readonly MethodInfo CallSiteRuntimeResolverResolve =
GetMethodInfo<Func<CallSiteRuntimeResolver, IServiceCallSite, ServiceProviderEngineScope, object>>((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<object, object>), 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<ServiceProviderEngineScope, object> 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<Func<ServiceProviderEngineScope, object>> BuildExpression(IServiceCallSite callSite)
{
var context = new CallSiteExpressionBuilderContext
{
ScopeParameter = ScopeParameter
};
var serviceExpression = VisitCallSite(callSite, context);
if (context.RequiresResolvedServices)
{
return Expression.Lambda<Func<ServiceProviderEngineScope, object>>(
Expression.Block(
new [] { ResolvedServices },
ResolvedServicesVariableAssignment,
Lock(serviceExpression, ResolvedServices)),
ScopeParameter);
}
return Expression.Lambda<Func<ServiceProviderEngineScope, object>>(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<object>()));
}
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<T>(Expression<T> 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));
}
}
}
@@ -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<ServiceDescriptor> serviceDescriptors, IServiceProviderEngineCallback callback) : base(serviceDescriptors, callback)
{
_expressionResolverBuilder = new ExpressionResolverBuilder(RuntimeResolver, this, Root);
}
protected override Func<ServiceProviderEngineScope, object> RealizeService(IServiceCallSite callSite)
{
var realizedService = _expressionResolverBuilder.Build(callSite);
RealizedServices[callSite.ServiceType] = realizedService;
return realizedService;
}
}
}
@@ -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<IServiceProvider, object> Factory { get; }
public FactoryCallSite(Type serviceType, Func<IServiceProvider, object> factory)
{
Factory = factory;
ServiceType = serviceType;
}
public Type ServiceType { get; }
public Type ImplementationType => null;
public CallSiteKind Kind { get; } = CallSiteKind.Factory;
}
}
@@ -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;
}
}
@@ -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);
}
}
@@ -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<object, ILEmitCallSiteAnalysisResult>
{
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);
}
}
@@ -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<ILEmitResolverBuilderContext, Expression>
{
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<IServiceProvider, object>[] 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<ServiceProviderEngineScope, object> 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<Func<IServiceProvider, object>>();
}
// 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<IServiceProvider, object>));
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<object>();
}
// 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<ServiceProviderEngineScope, object> 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<ServiceProviderEngineScope, object>)dynamicMethod.CreateDelegate(typeof(Func<ServiceProviderEngineScope, object>), 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<object, object>));
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);
}
}
}
@@ -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<object> Constants { get; set; }
public List<Func<IServiceProvider, object>> Factories { get; set; }
}
}
@@ -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<ServiceDescriptor> serviceDescriptors, IServiceProviderEngineCallback callback) : base(serviceDescriptors, callback)
{
_expressionResolverBuilder = new ILEmitResolverBuilder(RuntimeResolver, this, Root);
}
protected override Func<ServiceProviderEngineScope, object> RealizeService(IServiceCallSite callSite)
{
var realizedService = _expressionResolverBuilder.Build(callSite);
RealizedServices[callSite.ServiceType] = realizedService;
return realizedService;
}
}
}
@@ -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>
/// Summary description for IServiceCallSite
/// </summary>
internal interface IServiceCallSite
{
Type ServiceType { get; }
Type ImplementationType { get; }
CallSiteKind Kind { get; }
}
}
@@ -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; }
}
}
@@ -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);
}
}
@@ -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<ServiceDescriptor> serviceDescriptors, IServiceProviderEngineCallback callback) : base(serviceDescriptors, callback)
{
}
protected override Func<ServiceProviderEngineScope, object> RealizeService(IServiceCallSite callSite)
{
return scope =>
{
Func<ServiceProviderEngineScope, object> realizedService = p => RuntimeResolver.Resolve(callSite, p);
RealizedServices[callSite.ServiceType] = realizedService;
return realizedService(scope);
};
}
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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<Type, Func<ServiceProviderEngineScope, object>> _createServiceAccessor;
private bool _disposed;
protected ServiceProviderEngine(IEnumerable<ServiceDescriptor> 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<Type, Func<ServiceProviderEngineScope, object>>();
}
internal ConcurrentDictionary<Type, Func<ServiceProviderEngineScope, object>> 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<ServiceProviderEngineScope, object> 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<ServiceProviderEngineScope, object> CreateServiceAccessor(Type serviceType)
{
var callSite = CallSiteFactory.CreateCallSite(serviceType, new CallSiteChain());
if (callSite != null)
{
_callback?.OnCreate(callSite);
return RealizeService(callSite);
}
return _ => null;
}
}
}
@@ -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<object> _captureDisposableCallback;
private List<IDisposable> _disposables;
private bool _disposed;
public ServiceProviderEngineScope(ServiceProviderEngine engine)
{
Engine = engine;
}
internal Dictionary<object, object> ResolvedServices { get; } = new Dictionary<object, object>();
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<IDisposable>();
}
_disposables.Add(disposable);
}
}
}
return service;
}
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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));
}
}
}
@@ -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;
}
}
@@ -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
{
/// <summary>
/// The default IServiceProvider.
/// </summary>
public sealed class ServiceProvider : IServiceProvider, IDisposable, IServiceProviderEngineCallback
{
private readonly IServiceProviderEngine _engine;
private readonly CallSiteValidator _callSiteValidator;
internal ServiceProvider(IEnumerable<ServiceDescriptor> 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));
}
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType"></param>
/// <returns></returns>
public object GetService(Type serviceType) => _engine.GetService(serviceType);
/// <inheritdoc />
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);
}
}
}
@@ -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
}
}
@@ -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
{
/// <summary>
/// Options for configuring various behaviors of the default <see cref="IServiceProvider"/> implementation.
/// </summary>
public class ServiceProviderOptions
{
// Avoid allocating objects in the default case
internal static readonly ServiceProviderOptions Default = new ServiceProviderOptions();
/// <summary>
/// <c>true</c> to perform check verifying that scoped services never gets resolved from root provider; otherwise <c>false</c>.
/// </summary>
public bool ValidateScopes { get; set; }
internal ServiceProviderMode Mode { get; set; } = ServiceProviderMode.Dynamic;
}
}
@@ -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<Microsoft.Extensions.DependencyInjection.IServiceCollection>"
],
"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<Microsoft.Extensions.DependencyInjection.IServiceCollection>",
"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<Microsoft.Extensions.DependencyInjection.IServiceCollection>",
"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<Microsoft.Extensions.DependencyInjection.ServiceDescriptor>",
"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<Microsoft.Extensions.DependencyInjection.ServiceDescriptor>",
"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<Microsoft.Extensions.DependencyInjection.ServiceDescriptor>",
"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<Microsoft.Extensions.DependencyInjection.ServiceDescriptor>",
"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<Microsoft.Extensions.DependencyInjection.ServiceDescriptor>",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_Count",
"Parameters": [],
"ReturnType": "System.Int32",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "System.Collections.Generic.ICollection<Microsoft.Extensions.DependencyInjection.ServiceDescriptor>",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_IsReadOnly",
"Parameters": [],
"ReturnType": "System.Boolean",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "System.Collections.Generic.ICollection<Microsoft.Extensions.DependencyInjection.ServiceDescriptor>",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "Clear",
"Parameters": [],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "System.Collections.Generic.ICollection<Microsoft.Extensions.DependencyInjection.ServiceDescriptor>",
"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<Microsoft.Extensions.DependencyInjection.ServiceDescriptor>",
"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<Microsoft.Extensions.DependencyInjection.ServiceDescriptor>",
"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<Microsoft.Extensions.DependencyInjection.ServiceDescriptor>",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "GetEnumerator",
"Parameters": [],
"ReturnType": "System.Collections.Generic.IEnumerator<Microsoft.Extensions.DependencyInjection.ServiceDescriptor>",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "System.Collections.Generic.IEnumerable<Microsoft.Extensions.DependencyInjection.ServiceDescriptor>",
"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": []
}
]
}
@@ -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<object[]> TestServiceDescriptors(ServiceLifetime lifetime)
{
Func<object, object, bool> 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<PocoClass>), typeof(FakeService), lifetime) },
typeof(IFakeOpenGenericService<PocoClass>),
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<IFakeService>),
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<object, object, bool> 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<ServiceA>();
descriptors.AddScoped<ServiceB>();
descriptors.AddScoped<ServiceC>();
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<object>();
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<ServiceB>()), lifetime));
var disposables = new List<object>();
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<ServiceB>();
descriptors.AddTransient<ServiceC>();
var disposables = new List<object>();
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<object>();
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<ClassWithThrowingEmptyCtor>();
descriptors.AddTransient<ClassWithThrowingCtor>();
descriptors.AddTransient<IFakeService, FakeService>();
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<Exception>(() => compiledCallSite1(provider.Root));
Assert.Equal(nameof(ClassWithThrowingEmptyCtor), ex1.Message);
var ex2 = Assert.Throws<Exception>(() => compiledCallSite2(provider.Root));
Assert.Equal(nameof(ClassWithThrowingCtor), ex2.Message);
}
private class ServiceD
{
public ServiceD(IEnumerable<ServiceA> 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<ServiceProviderEngineScope, object> CompileCallSite(IServiceCallSite callSite, ServiceProviderEngine engine)
{
return new ExpressionResolverBuilder(CallSiteRuntimeResolver, engine, engine.Root).Build(callSite);
}
}
}
@@ -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<SelfCircularDependency>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<SelfCircularDependency>());
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 -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependency";
var serviceProvider = new ServiceCollection()
.AddTransient<SelfCircularDependency>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<IEnumerable<SelfCircularDependency>>());
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<string>'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string> -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string>";
var serviceProvider = new ServiceCollection()
.AddTransient<SelfCircularDependencyGeneric<string>>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<SelfCircularDependencyGeneric<string>>());
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<string>'." +
Environment.NewLine +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<int> -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string> -> " +
"Microsoft.Extensions.DependencyInjection.Tests.Fakes.SelfCircularDependencyGeneric<string>";
var serviceProvider = new ServiceCollection()
.AddTransient<SelfCircularDependencyGeneric<int>>()
.AddTransient<SelfCircularDependencyGeneric<string>>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<SelfCircularDependencyGeneric<int>>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void NoCircularDependencyGeneric()
{
var serviceProvider = new ServiceCollection()
.AddSingleton(new SelfCircularDependencyGeneric<string>())
.AddTransient<SelfCircularDependencyGeneric<int>>()
.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<SelfCircularDependencyGeneric<int>>();
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<ISelfCircularDependencyWithInterface, SelfCircularDependencyWithInterface>()
.AddTransient<SelfCircularDependencyWithInterface>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<SelfCircularDependencyWithInterface>());
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<DirectCircularDependencyA>()
.AddSingleton<DirectCircularDependencyB>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<DirectCircularDependencyA>());
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<IndirectCircularDependencyA>()
.AddTransient<IndirectCircularDependencyB>()
.AddTransient<IndirectCircularDependencyC>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<IndirectCircularDependencyA>());
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void NoCircularDependencySameTypeMultipleTimes()
{
var serviceProvider = new ServiceCollection()
.AddTransient<NoCircularDependencySameTypeMultipleTimesA>()
.AddTransient<NoCircularDependencySameTypeMultipleTimesB>()
.AddTransient<NoCircularDependencySameTypeMultipleTimesC>()
.BuildServiceProvider();
var resolvedService = serviceProvider.GetRequiredService<NoCircularDependencySameTypeMultipleTimesA>();
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<DependencyOnCircularDependency>()
.AddTransient<DirectCircularDependencyA>()
.AddTransient<DirectCircularDependencyB>()
.BuildServiceProvider();
var exception = Assert.Throws<InvalidOperationException>(() =>
serviceProvider.GetRequiredService<DependencyOnCircularDependency>());
Assert.Equal(expectedMessage, exception.Message);
}
}
}
@@ -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()
{
}
}
}
@@ -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)
{
}
}
}
@@ -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)
{
}
}
}
@@ -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)
{
}
}
}
@@ -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
{
}
}
@@ -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)
{
}
}
}
@@ -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)
{
}
}
}
@@ -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)
{
}
}
}
@@ -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)
{
}
}
}
@@ -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)
{
}
}
}
@@ -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()
{
}
}
}
@@ -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)
{
}
}
}
@@ -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<TDependency>
{
public SelfCircularDependencyGeneric(SelfCircularDependencyGeneric<string> dependency)
{
}
public SelfCircularDependencyGeneric()
{
}
}
}
@@ -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)
{
}
}
}
@@ -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)
{
}
}
}
@@ -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();
}
}
}
@@ -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 { }
}
}
@@ -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)
{
}
}
}
@@ -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)
{
}
}
}
@@ -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)
{
}
}
}
@@ -0,0 +1,9 @@
namespace Microsoft.Extensions.DependencyInjection.Fakes
{
public struct StructService
{
public StructService(IServiceScopeFactory scopeFactory)
{
}
}
}
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(StandardTestTfms)</TargetFrameworks>
<RootNamespace>Microsoft.Extensions.DependencyInjection</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\src\Microsoft.Extensions.DependencyInjection.csproj" />
<ProjectReference Include="..\..\DI.Specification.Tests\src\Microsoft.Extensions.DependencyInjection.Specification.Tests.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Testing" />
</ItemGroup>
<ItemGroup>
<None Update="xunit.runner.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>
@@ -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);
}
}
}
@@ -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<Action<IServiceCollection>, Type, Type, ServiceLifetime>
{
{ collection => collection.AddTransient(serviceType, implementationType), serviceType, implementationType, ServiceLifetime.Transient },
{ collection => collection.AddTransient<IFakeService, FakeService>(), serviceType, implementationType, ServiceLifetime.Transient },
{ collection => collection.AddTransient<IFakeService>(), serviceType, serviceType, ServiceLifetime.Transient },
{ collection => collection.AddTransient(implementationType), implementationType, implementationType, ServiceLifetime.Transient },
{ collection => collection.AddScoped(serviceType, implementationType), serviceType, implementationType, ServiceLifetime.Scoped },
{ collection => collection.AddScoped<IFakeService, FakeService>(), serviceType, implementationType, ServiceLifetime.Scoped },
{ collection => collection.AddScoped<IFakeService>(), serviceType, serviceType, ServiceLifetime.Scoped },
{ collection => collection.AddScoped(implementationType), implementationType, implementationType, ServiceLifetime.Scoped },
{ collection => collection.AddSingleton(serviceType, implementationType), serviceType, implementationType, ServiceLifetime.Singleton },
{ collection => collection.AddSingleton<IFakeService, FakeService>(), serviceType, implementationType, ServiceLifetime.Singleton },
{ collection => collection.AddSingleton<IFakeService>(), serviceType, serviceType, ServiceLifetime.Singleton },
{ collection => collection.AddSingleton(implementationType), implementationType, implementationType, ServiceLifetime.Singleton },
};
}
}
[Theory]
[MemberData(nameof(AddImplementationTypeData))]
public void AddWithTypeAddsServiceWithRightLifecyle(Action<IServiceCollection> 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<Action<IServiceCollection>, Type, Type, ServiceLifetime>
{
{ collection => collection.AddTransient(serviceType, s => new FakeService()), serviceType, objectType, ServiceLifetime.Transient },
{ collection => collection.AddTransient<IFakeService>(s => new FakeService()), serviceType, serviceType, ServiceLifetime.Transient },
{ collection => collection.AddTransient<IFakeService, FakeService>(s => new FakeService()), serviceType, implementationType, ServiceLifetime.Transient },
{ collection => collection.AddScoped(serviceType, s => new FakeService()), serviceType, objectType, ServiceLifetime.Scoped },
{ collection => collection.AddScoped<IFakeService>(s => new FakeService()), serviceType, serviceType, ServiceLifetime.Scoped },
{ collection => collection.AddScoped<IFakeService, FakeService>(s => new FakeService()), serviceType, implementationType, ServiceLifetime.Scoped },
{ collection => collection.AddSingleton(serviceType, s => new FakeService()), serviceType, objectType, ServiceLifetime.Singleton },
{ collection => collection.AddSingleton<IFakeService>(s => new FakeService()), serviceType, serviceType, ServiceLifetime.Singleton },
{ collection => collection.AddSingleton<IFakeService, FakeService>(s => new FakeService()), serviceType, implementationType, ServiceLifetime.Singleton },
};
}
}
[Theory]
[MemberData(nameof(AddImplementationFactoryData))]
public void AddWithFactoryAddsServiceWithRightLifecyle(
Action<IServiceCollection> 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<Action<IServiceCollection>>
{
{ collection => collection.AddSingleton<IFakeService>(_instance) },
{ collection => collection.AddSingleton(typeof(IFakeService), _instance) },
};
}
}
[Theory]
[MemberData(nameof(AddSingletonData))]
public void AddSingleton_AddsWithSingletonLifecycle(Action<IServiceCollection> 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<IServiceCollection> addAction)
{
// Arrange
var collection = new ServiceCollection();
addAction(collection);
var d = ServiceDescriptor.Transient<IFakeService, FakeService>();
// 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<Action<IServiceCollection>, Type, Type, ServiceLifetime>
{
{ collection => collection.TryAddTransient(serviceType, implementationType), serviceType, implementationType, ServiceLifetime.Transient },
{ collection => collection.TryAddTransient<IFakeService, FakeService>(), serviceType, implementationType, ServiceLifetime.Transient },
{ collection => collection.TryAddTransient<IFakeService>(), serviceType, serviceType, ServiceLifetime.Transient },
{ collection => collection.TryAddTransient(implementationType), implementationType, implementationType, ServiceLifetime.Transient },
{ collection => collection.TryAddScoped(serviceType, implementationType), serviceType, implementationType, ServiceLifetime.Scoped },
{ collection => collection.TryAddScoped<IFakeService, FakeService>(), serviceType, implementationType, ServiceLifetime.Scoped },
{ collection => collection.TryAddScoped<IFakeService>(), serviceType, serviceType, ServiceLifetime.Scoped },
{ collection => collection.TryAddScoped(implementationType), implementationType, implementationType, ServiceLifetime.Scoped },
{ collection => collection.TryAddSingleton(serviceType, implementationType), serviceType, implementationType, ServiceLifetime.Singleton },
{ collection => collection.TryAddSingleton<IFakeService, FakeService>(), serviceType, implementationType, ServiceLifetime.Singleton },
{ collection => collection.TryAddSingleton<IFakeService>(), serviceType, serviceType, ServiceLifetime.Singleton },
{ collection => collection.TryAddSingleton(implementationType), implementationType, implementationType, ServiceLifetime.Singleton },
};
}
}
[Theory]
[MemberData(nameof(TryAddImplementationTypeData))]
public void TryAdd_WithType_AddsService(
Action<IServiceCollection> 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<IServiceCollection> 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<IFakeService, FakeService>();
// 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, Type, Type, ServiceLifetime>
{
{ ServiceDescriptor.Transient<IFakeService, FakeService>(), serviceType, implementationType, ServiceLifetime.Transient },
{ ServiceDescriptor.Transient<IFakeService, FakeService>(s => new FakeService()), serviceType, implementationType, ServiceLifetime.Transient },
{ ServiceDescriptor.Scoped<IFakeService, FakeService>(), serviceType, implementationType, ServiceLifetime.Scoped },
{ ServiceDescriptor.Scoped<IFakeService, FakeService>(s => new FakeService()), serviceType, implementationType, ServiceLifetime.Scoped },
{ ServiceDescriptor.Singleton<IFakeService, FakeService>(), serviceType, implementationType, ServiceLifetime.Singleton },
{ ServiceDescriptor.Singleton<IFakeService, FakeService >(s => new FakeService()), serviceType, implementationType, ServiceLifetime.Singleton },
{ ServiceDescriptor.Singleton<IFakeService>(_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, Type, Type>
{
{ ServiceDescriptor.Transient<IFakeService>(s => new FakeService()), serviceType, serviceType },
{ ServiceDescriptor.Transient(serviceType, s => new FakeService()), serviceType, objectType },
{ ServiceDescriptor.Scoped<IFakeService>(s => new FakeService()), serviceType, serviceType },
{ ServiceDescriptor.Scoped(serviceType, s => new FakeService()), serviceType, objectType },
{ ServiceDescriptor.Singleton<IFakeService>(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<IFakeService>();
// Assert
Assert.Equal(new[] { descriptor }, collection);
}
}
}
@@ -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<InvalidOperationException>(() => 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<TransientCallSite>(callSite);
Assert.IsType<CreateInstanceCallSite>(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<TransientCallSite>(callSite);
var constructorCallSite = Assert.IsType<ConstructorCallSite>(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<TransientCallSite>(callSite);
var constructorCallSite = Assert.IsType<ConstructorCallSite>(transientCall.ServiceCallSite);
Assert.Equal(
new[] { typeof(IEnumerable<IFakeService>), typeof(IEnumerable<IFactoryService>) },
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<TransientCallSite>(callSite);
Assert.IsType<CreateInstanceCallSite>(transientCall.ServiceCallSite);
}
public static TheoryData CreateCallSite_PicksConstructorWithTheMostNumberOfResolvedParametersData =>
new TheoryData<Type, Func<Type, object>, 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<IFakeService>) }
},
{
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<IFakeService>) }
}
};
[Theory]
[MemberData(nameof(CreateCallSite_PicksConstructorWithTheMostNumberOfResolvedParametersData))]
public void CreateCallSite_PicksConstructorWithTheMostNumberOfResolvedParameters(
Type type,
Func<Type, object> callSiteFactory,
Type[] expectedConstructorParameters)
{
// Act
var callSite = callSiteFactory(type);
// Assert
var transientCall = Assert.IsType<TransientCallSite>(callSite);
var constructorCallSite = Assert.IsType<ConstructorCallSite>(transientCall.ServiceCallSite);
Assert.Equal(expectedConstructorParameters, GetParameters(constructorCallSite));
}
public static TheoryData CreateCallSite_ConsidersConstructorsWithDefaultValuesData =>
new TheoryData<Func<Type, object>, 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<Type, object> callSiteFactory,
Type[] expectedConstructorParameters)
{
// Arrange
var type = typeof(TypeWithDefaultConstructorParameters);
// Act
var callSite = callSiteFactory(type);
// Assert
var transientCall = Assert.IsType<TransientCallSite>(callSite);
var constructorCallSite = Assert.IsType<ConstructorCallSite>(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<InvalidOperationException>(
() => 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<InvalidOperationException>(
() => 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, Func<Type, object>, 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<IFakeService>) }
}
},
{
typeof(TypeWithUnresolvableEnumerableConstructors),
GetCallSiteFactory(
new ServiceDescriptor(typeof(TypeWithUnresolvableEnumerableConstructors), typeof(TypeWithUnresolvableEnumerableConstructors), ServiceLifetime.Transient),
new ServiceDescriptor(typeof(IFactoryService), typeof(FakeService), ServiceLifetime.Transient)
),
new[]
{
new[] { typeof(IEnumerable<IFakeService>) },
new[] { typeof(IFactoryService) }
}
},
};
[Theory]
[MemberData(nameof(CreateCallSite_ThrowsIfMultipleNonOverlappingConstructorsCanBeResolvedData))]
public void CreateCallSite_ThrowsIfMultipleNonOverlappingConstructorsCanBeResolved(
Type type,
Func<Type, object> 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<InvalidOperationException>(
() => 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<InvalidOperationException>(
() => callSiteFactory(type));
Assert.StartsWith(expectedMessage, ex.Message);
}
private static Func<Type, object> 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<Type> 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));
}
}
@@ -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)
{
}
}
}
@@ -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<IFakeService> fakeServices)
{
}
public TypeWithEnumerableConstructors(
IEnumerable<IFakeService> fakeServices,
IEnumerable<IFactoryService> factoryServices)
{
}
}
}
@@ -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<IFakeService> logger)
{
}
public TypeWithGenericServices(
IFakeMultipleService multipleService,
IFakeService fakeService)
{
}
public TypeWithGenericServices(
IFakeService fakeService,
IFactoryService factoryService,
IFakeOpenGenericService<IFakeService> logger)
{
}
}
}
@@ -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)
{
}
}
}
@@ -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
{
}
}
@@ -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)
{
}
}
}
@@ -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)
{
}
}
}
@@ -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)
{
}
}
}
@@ -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)
{
}
}
}
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more