Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
Expand All@@ -10,13 +11,25 @@
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.Internal;

#if NETCOREAPP
[assembly: System.Reflection.Metadata.MetadataUpdateHandler(typeof(Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ActivatorUtilitiesUpdateHandler))]
#endif

namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Helper code for the various activator services.
/// </summary>
public static class ActivatorUtilities
{
#if NETCOREAPP
// Support caching of constructor metadata for the common case of types in non-collectible assemblies.
private static readonly ConcurrentDictionary<Type, ConstructorInfoEx[]> s_constructorInfos = new();

// Support caching of constructor metadata for types in collectible assemblies.
private static readonly Lazy<ConditionalWeakTable<Type, ConstructorInfoEx[]>> s_collectibleConstructorInfos = new();
#endif

#if NET8_0_OR_GREATER
// Maximum number of fixed arguments for ConstructorInvoker.Invoke(arg1, etc).
private const int FixedArgumentThreshold = 4;
Expand DownExpand Up@@ -47,6 +60,17 @@ public static object CreateInstance(
throw new InvalidOperationException(SR.CannotCreateAbstractClasses);
}

ConstructorInfoEx[]? constructors;
#if NETCOREAPP
if (!s_constructorInfos.TryGetValue(instanceType, out constructors))
{
constructors = GetOrAddConstructors(instanceType);
}
#else
constructors = CreateConstructorInfoExs(instanceType);
#endif

ConstructorInfoEx? constructor;
IServiceProviderIsService? serviceProviderIsService = provider.GetService<IServiceProviderIsService>();
// if container supports using IServiceProviderIsService, we try to find the longest ctor that
// (a) matches all parameters given to CreateInstance
Expand All@@ -61,10 +85,11 @@ public static object CreateInstance(
ConstructorMatcher bestMatcher = default;
bool multipleBestLengthFound = false;

foreach (ConstructorInfo? constructor in instanceType.GetConstructors())
for (int i = 0; i < constructors.Length; i++)
{
var matcher = new ConstructorMatcher(constructor);
bool isPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false);
constructor = constructors[i];
ConstructorMatcher matcher = new(constructor);
bool isPreferred = constructor.IsPreferred;
int length = matcher.Match(parameters, serviceProviderIsService);

if (isPreferred)
Expand DownExpand Up@@ -105,18 +130,79 @@ public static object CreateInstance(
}
}

Type?[] argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
Type?[] argumentTypes;
if (parameters.Length == 0)
{
argumentTypes[i] = parameters[i]?.GetType();
argumentTypes = Type.EmptyTypes;
}
else
{
argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
{
argumentTypes[i] = parameters[i]?.GetType();
}
}

FindApplicableConstructor(instanceType, argumentTypes, out ConstructorInfo constructorInfo, out int?[] parameterMap);
var constructorMatcher = new ConstructorMatcher(constructorInfo);

// Find the ConstructorInfoEx from the given constructorInfo.
constructor = null;
foreach (ConstructorInfoEx ctor in constructors)
Comment thread
steveharter marked this conversation as resolved.
{
if (ReferenceEquals(ctor.Info, constructorInfo))
{
constructor = ctor;
break;
}
}

Debug.Assert(constructor != null);

var constructorMatcher = new ConstructorMatcher(constructor);
constructorMatcher.MapParameters(parameterMap, parameters);
return constructorMatcher.CreateInstance(provider);
}

#if NETCOREAPP
private static ConstructorInfoEx[] GetOrAddConstructors(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
// Not found. Do the slower work of checking for the value in the correct cache.
// Null and non-collectible load contexts use the default cache.
if (!type.Assembly.IsCollectible)
{
return s_constructorInfos.GetOrAdd(type, CreateConstructorInfoExs(type));
}

// Collectible load contexts should use the ConditionalWeakTable so they can be unloaded.
if (s_collectibleConstructorInfos.Value.TryGetValue(type, out ConstructorInfoEx[]? value))
{
return value;
}

value = CreateConstructorInfoExs(type);

// ConditionalWeakTable doesn't support GetOrAdd() so use AddOrUpdate(). This means threads
// can have different instances for the same type, but that is OK since they are equivalent.
s_collectibleConstructorInfos.Value.AddOrUpdate(type, value);
return value;
}
#endif // NETCOREAPP

private static ConstructorInfoEx[] CreateConstructorInfoExs(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
ConstructorInfo[] constructors = type.GetConstructors();
ConstructorInfoEx[]? value = new ConstructorInfoEx[constructors.Length];
for (int i = 0; i < constructors.Length; i++)
{
value[i] = new ConstructorInfoEx(constructors[i]);
}

return value;
}

/// <summary>
/// Create a delegate that will instantiate a type with constructor arguments provided directly
/// and/or from an <see cref="IServiceProvider"/>.
Expand DownExpand Up@@ -551,58 +637,82 @@ private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters,
return true;
}

private static object? GetService(IServiceProvider serviceProvider, ParameterInfo parameterInfo)
private sealed class ConstructorInfoEx
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public readonly ConstructorInfo Info;
public readonly ParameterInfo[] Parameters;
public readonly bool IsPreferred;
private readonly object?[]? _parameterKeys;

public ConstructorInfoEx(ConstructorInfo constructor)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
Info = constructor;
Parameters = constructor.GetParameters();
IsPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false);

for (int i = 0; i < Parameters.Length; i++)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
FromKeyedServicesAttribute? attr = (FromKeyedServicesAttribute?)
Attribute.GetCustomAttribute(Parameters[i], typeof(FromKeyedServicesAttribute), inherit: false);

if (attr is not null)
{
_parameterKeys ??= new object?[Parameters.Length];
_parameterKeys[i] = attr.Key;
}
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
// Try non keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}

private static bool IsService(IServiceProviderIsService serviceProviderIsService, ParameterInfo parameterInfo)
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public bool IsService(IServiceProviderIsService serviceProviderIsService, int parameterIndex)
{
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);

// Use non-keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}
// Try non keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}

private static bool TryGetServiceKey(ParameterInfo parameterInfo, out object? key)
{
foreach (var attribute in parameterInfo.GetCustomAttributes<FromKeyedServicesAttribute>(false))
public object? GetService(IServiceProvider serviceProvider, int parameterIndex)
{
key = attribute.Key;
return true;
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}

// Use non-keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}
key = null;
return false;
}

private readonly struct ConstructorMatcher
{
private readonly ConstructorInfo _constructor;
private readonly ParameterInfo[] _parameters;
private readonly ConstructorInfoEx _constructor;
private readonly object?[] _parameterValues;

public ConstructorMatcher(ConstructorInfo constructor)
public ConstructorMatcher(ConstructorInfoEx constructor)
{
_constructor = constructor;
_parameters = _constructor.GetParameters();
_parameterValues = new object?[_parameters.Length];
_parameterValues = new object[constructor.Parameters.Length];
}

public int Match(object[] givenParameters, IServiceProviderIsService serviceProviderIsService)
Expand All@@ -612,10 +722,10 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
Type? givenType = givenParameters[givenIndex]?.GetType();
bool givenMatched = false;

for (int applyIndex = 0; applyIndex < _parameters.Length; applyIndex++)
for (int applyIndex = 0; applyIndex < _constructor.Parameters.Length; applyIndex++)
{
if (_parameterValues[applyIndex] == null &&
_parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
_constructor.Parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
{
givenMatched = true;
_parameterValues[applyIndex] = givenParameters[givenIndex];
Expand All@@ -630,12 +740,12 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}

// confirms the rest of ctor arguments match either as a parameter with a default value or as a service registered
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (_parameterValues[i] == null &&
!IsService(serviceProviderIsService, _parameters[i]))
!_constructor.IsService(serviceProviderIsService, i))
{
if (ParameterDefaultValue.TryGetDefaultValue(_parameters[i], out object? defaultValue))
if (ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[i], out object? defaultValue))
{
_parameterValues[i] = defaultValue;
}
Expand All@@ -646,21 +756,21 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}
}

return _parameters.Length;
return _constructor.Parameters.Length;
}

public object CreateInstance(IServiceProvider provider)
{
for (int index = 0; index < _parameters.Length; index++)
for (int index = 0; index < _constructor.Parameters.Length; index++)
{
if (_parameterValues[index] == null)
{
object? value = GetService(provider, _parameters[index]);
object? value = _constructor.GetService(provider, index);
if (value == null)
{
if (!ParameterDefaultValue.TryGetDefaultValue(_parameters[index], out object? defaultValue))
if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[index], out object? defaultValue))
{
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _parameters[index].ParameterType, _constructor.DeclaringType));
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _constructor.Parameters[index].ParameterType, _constructor.Info.DeclaringType));
}
else
{
Expand All@@ -677,7 +787,7 @@ public object CreateInstance(IServiceProvider provider)
#if NETFRAMEWORK || NETSTANDARD2_0
try
{
return _constructor.Invoke(_parameterValues);
return _constructor.Info.Invoke(_parameterValues);
}
catch (TargetInvocationException ex) when (ex.InnerException != null)
{
Expand All@@ -686,13 +796,13 @@ public object CreateInstance(IServiceProvider provider)
throw;
}
#else
return _constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
return _constructor.Info.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
#endif
}

public void MapParameters(int?[] parameterMap, object[] givenParameters)
{
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (parameterMap[i] != null)
{
Expand DownExpand Up@@ -974,5 +1084,20 @@ private static object ReflectionFactoryCanonical(
return constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, constructorArguments, culture: null);
}
#endif // NET8_0_OR_GREATER

#if NETCOREAPP
internal static class ActivatorUtilitiesUpdateHandler
{
public static void ClearCache(Type[]? _)
{
// Ignore the Type[] argument; just clear the caches.
s_constructorInfos.Clear();
if (s_collectibleConstructorInfos.IsValueCreated)
{
s_collectibleConstructorInfos.Value.Clear();
}
}
}
#endif
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Extensions.DependencyInjection;

namespace CollectibleAssembly
{
public class ClassToCreate
{
public object ClassAsCtorArgument { get; set; }

public ClassToCreate(ClassAsCtorArgument obj) { ClassAsCtorArgument = obj; }

public static object Create(ServiceProvider provider)
{
// Both the type to create (ClassToCreate) and the ctor's arg type (ClassAsCtorArgument) are
// located in this assembly, so both types need to be GC'd for this assembly to be collected.
return ActivatorUtilities.CreateInstance<ClassToCreate>(provider, new ClassAsCtorArgument());
}
}

public class ClassAsCtorArgument
{
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
Expand All@@ -10,13 +11,25 @@
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.Internal;

#if NETCOREAPP
[assembly: System.Reflection.Metadata.MetadataUpdateHandler(typeof(Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ActivatorUtilitiesUpdateHandler))]
#endif

namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Helper code for the various activator services.
/// </summary>
public static class ActivatorUtilities
{
#if NETCOREAPP
// Support caching of constructor metadata for the common case of types in non-collectible assemblies.
private static readonly ConcurrentDictionary<Type, ConstructorInfoEx[]> s_constructorInfos = new();

// Support caching of constructor metadata for types in collectible assemblies.
private static readonly Lazy<ConditionalWeakTable<Type, ConstructorInfoEx[]>> s_collectibleConstructorInfos = new();
#endif

#if NET8_0_OR_GREATER
// Maximum number of fixed arguments for ConstructorInvoker.Invoke(arg1, etc).
private const int FixedArgumentThreshold = 4;
Expand DownExpand Up@@ -47,6 +60,17 @@ public static object CreateInstance(
throw new InvalidOperationException(SR.CannotCreateAbstractClasses);
}

ConstructorInfoEx[]? constructors;
#if NETCOREAPP
if (!s_constructorInfos.TryGetValue(instanceType, out constructors))
{
constructors = GetOrAddConstructors(instanceType);
}
#else
constructors = CreateConstructorInfoExs(instanceType);
#endif

ConstructorInfoEx? constructor;
IServiceProviderIsService? serviceProviderIsService = provider.GetService<IServiceProviderIsService>();
// if container supports using IServiceProviderIsService, we try to find the longest ctor that
// (a) matches all parameters given to CreateInstance
Expand All@@ -61,10 +85,11 @@ public static object CreateInstance(
ConstructorMatcher bestMatcher = default;
bool multipleBestLengthFound = false;

foreach (ConstructorInfo? constructor in instanceType.GetConstructors())
for (int i = 0; i < constructors.Length; i++)
{
var matcher = new ConstructorMatcher(constructor);
bool isPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false);
constructor = constructors[i];
ConstructorMatcher matcher = new(constructor);
bool isPreferred = constructor.IsPreferred;
int length = matcher.Match(parameters, serviceProviderIsService);

if (isPreferred)
Expand DownExpand Up@@ -105,18 +130,79 @@ public static object CreateInstance(
}
}

Type?[] argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
Type?[] argumentTypes;
if (parameters.Length == 0)
{
argumentTypes[i] = parameters[i]?.GetType();
argumentTypes = Type.EmptyTypes;
}
else
{
argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
{
argumentTypes[i] = parameters[i]?.GetType();
}
}

FindApplicableConstructor(instanceType, argumentTypes, out ConstructorInfo constructorInfo, out int?[] parameterMap);
var constructorMatcher = new ConstructorMatcher(constructorInfo);

// Find the ConstructorInfoEx from the given constructorInfo.
constructor = null;
foreach (ConstructorInfoEx ctor in constructors)
Comment thread
steveharter marked this conversation as resolved.
{
if (ReferenceEquals(ctor.Info, constructorInfo))
{
constructor = ctor;
break;
}
}

Debug.Assert(constructor != null);

var constructorMatcher = new ConstructorMatcher(constructor);
constructorMatcher.MapParameters(parameterMap, parameters);
return constructorMatcher.CreateInstance(provider);
}

#if NETCOREAPP
private static ConstructorInfoEx[] GetOrAddConstructors(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
// Not found. Do the slower work of checking for the value in the correct cache.
// Null and non-collectible load contexts use the default cache.
if (!type.Assembly.IsCollectible)
{
return s_constructorInfos.GetOrAdd(type, CreateConstructorInfoExs(type));
}

// Collectible load contexts should use the ConditionalWeakTable so they can be unloaded.
if (s_collectibleConstructorInfos.Value.TryGetValue(type, out ConstructorInfoEx[]? value))
{
return value;
}

value = CreateConstructorInfoExs(type);

// ConditionalWeakTable doesn't support GetOrAdd() so use AddOrUpdate(). This means threads
// can have different instances for the same type, but that is OK since they are equivalent.
s_collectibleConstructorInfos.Value.AddOrUpdate(type, value);
return value;
}
#endif // NETCOREAPP

private static ConstructorInfoEx[] CreateConstructorInfoExs(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
ConstructorInfo[] constructors = type.GetConstructors();
ConstructorInfoEx[]? value = new ConstructorInfoEx[constructors.Length];
for (int i = 0; i < constructors.Length; i++)
{
value[i] = new ConstructorInfoEx(constructors[i]);
}

return value;
}

/// <summary>
/// Create a delegate that will instantiate a type with constructor arguments provided directly
/// and/or from an <see cref="IServiceProvider"/>.
Expand DownExpand Up@@ -551,58 +637,82 @@ private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters,
return true;
}

private static object? GetService(IServiceProvider serviceProvider, ParameterInfo parameterInfo)
private sealed class ConstructorInfoEx
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public readonly ConstructorInfo Info;
public readonly ParameterInfo[] Parameters;
public readonly bool IsPreferred;
private readonly object?[]? _parameterKeys;

public ConstructorInfoEx(ConstructorInfo constructor)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
Info = constructor;
Parameters = constructor.GetParameters();
IsPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false);

for (int i = 0; i < Parameters.Length; i++)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
FromKeyedServicesAttribute? attr = (FromKeyedServicesAttribute?)
Attribute.GetCustomAttribute(Parameters[i], typeof(FromKeyedServicesAttribute), inherit: false);

if (attr is not null)
{
_parameterKeys ??= new object?[Parameters.Length];
_parameterKeys[i] = attr.Key;
}
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
// Try non keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}

private static bool IsService(IServiceProviderIsService serviceProviderIsService, ParameterInfo parameterInfo)
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public bool IsService(IServiceProviderIsService serviceProviderIsService, int parameterIndex)
{
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);

// Use non-keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}
// Try non keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}

private static bool TryGetServiceKey(ParameterInfo parameterInfo, out object? key)
{
foreach (var attribute in parameterInfo.GetCustomAttributes<FromKeyedServicesAttribute>(false))
public object? GetService(IServiceProvider serviceProvider, int parameterIndex)
{
key = attribute.Key;
return true;
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}

// Use non-keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}
key = null;
return false;
}

private readonly struct ConstructorMatcher
{
private readonly ConstructorInfo _constructor;
private readonly ParameterInfo[] _parameters;
private readonly ConstructorInfoEx _constructor;
private readonly object?[] _parameterValues;

public ConstructorMatcher(ConstructorInfo constructor)
public ConstructorMatcher(ConstructorInfoEx constructor)
{
_constructor = constructor;
_parameters = _constructor.GetParameters();
_parameterValues = new object?[_parameters.Length];
_parameterValues = new object[constructor.Parameters.Length];
}

public int Match(object[] givenParameters, IServiceProviderIsService serviceProviderIsService)
Expand All@@ -612,10 +722,10 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
Type? givenType = givenParameters[givenIndex]?.GetType();
bool givenMatched = false;

for (int applyIndex = 0; applyIndex < _parameters.Length; applyIndex++)
for (int applyIndex = 0; applyIndex < _constructor.Parameters.Length; applyIndex++)
{
if (_parameterValues[applyIndex] == null &&
_parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
_constructor.Parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
{
givenMatched = true;
_parameterValues[applyIndex] = givenParameters[givenIndex];
Expand All@@ -630,12 +740,12 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}

// confirms the rest of ctor arguments match either as a parameter with a default value or as a service registered
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (_parameterValues[i] == null &&
!IsService(serviceProviderIsService, _parameters[i]))
!_constructor.IsService(serviceProviderIsService, i))
{
if (ParameterDefaultValue.TryGetDefaultValue(_parameters[i], out object? defaultValue))
if (ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[i], out object? defaultValue))
{
_parameterValues[i] = defaultValue;
}
Expand All@@ -646,21 +756,21 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}
}

return _parameters.Length;
return _constructor.Parameters.Length;
}

public object CreateInstance(IServiceProvider provider)
{
for (int index = 0; index < _parameters.Length; index++)
for (int index = 0; index < _constructor.Parameters.Length; index++)
{
if (_parameterValues[index] == null)
{
object? value = GetService(provider, _parameters[index]);
object? value = _constructor.GetService(provider, index);
if (value == null)
{
if (!ParameterDefaultValue.TryGetDefaultValue(_parameters[index], out object? defaultValue))
if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[index], out object? defaultValue))
{
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _parameters[index].ParameterType, _constructor.DeclaringType));
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _constructor.Parameters[index].ParameterType, _constructor.Info.DeclaringType));
}
else
{
Expand All@@ -677,7 +787,7 @@ public object CreateInstance(IServiceProvider provider)
#if NETFRAMEWORK || NETSTANDARD2_0
try
{
return _constructor.Invoke(_parameterValues);
return _constructor.Info.Invoke(_parameterValues);
}
catch (TargetInvocationException ex) when (ex.InnerException != null)
{
Expand All@@ -686,13 +796,13 @@ public object CreateInstance(IServiceProvider provider)
throw;
}
#else
return _constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
return _constructor.Info.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
#endif
}

public void MapParameters(int?[] parameterMap, object[] givenParameters)
{
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (parameterMap[i] != null)
{
Expand DownExpand Up@@ -974,5 +1084,20 @@ private static object ReflectionFactoryCanonical(
return constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, constructorArguments, culture: null);
}
#endif // NET8_0_OR_GREATER

#if NETCOREAPP
internal static class ActivatorUtilitiesUpdateHandler
{
public static void ClearCache(Type[]? _)
{
// Ignore the Type[] argument; just clear the caches.
s_constructorInfos.Clear();
if (s_collectibleConstructorInfos.IsValueCreated)
{
s_collectibleConstructorInfos.Value.Clear();
}
}
}
#endif
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Extensions.DependencyInjection;

namespace CollectibleAssembly
{
public class ClassToCreate
{
public object ClassAsCtorArgument { get; set; }

public ClassToCreate(ClassAsCtorArgument obj) { ClassAsCtorArgument = obj; }

public static object Create(ServiceProvider provider)
{
// Both the type to create (ClassToCreate) and the ctor's arg type (ClassAsCtorArgument) are
// located in this assembly, so both types need to be GC'd for this assembly to be collected.
return ActivatorUtilities.CreateInstance<ClassToCreate>(provider, new ClassAsCtorArgument());
}
}

public class ClassAsCtorArgument
{
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
Expand All@@ -10,13 +11,25 @@
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.Internal;

#if NETCOREAPP
[assembly: System.Reflection.Metadata.MetadataUpdateHandler(typeof(Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ActivatorUtilitiesUpdateHandler))]
#endif

namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Helper code for the various activator services.
/// </summary>
public static class ActivatorUtilities
{
#if NETCOREAPP
// Support caching of constructor metadata for the common case of types in non-collectible assemblies.
private static readonly ConcurrentDictionary<Type, ConstructorInfoEx[]> s_constructorInfos = new();

// Support caching of constructor metadata for types in collectible assemblies.
private static readonly Lazy<ConditionalWeakTable<Type, ConstructorInfoEx[]>> s_collectibleConstructorInfos = new();
#endif

#if NET8_0_OR_GREATER
// Maximum number of fixed arguments for ConstructorInvoker.Invoke(arg1, etc).
private const int FixedArgumentThreshold = 4;
Expand DownExpand Up@@ -47,6 +60,17 @@ public static object CreateInstance(
throw new InvalidOperationException(SR.CannotCreateAbstractClasses);
}

ConstructorInfoEx[]? constructors;
#if NETCOREAPP
if (!s_constructorInfos.TryGetValue(instanceType, out constructors))
{
constructors = GetOrAddConstructors(instanceType);
}
#else
constructors = CreateConstructorInfoExs(instanceType);
#endif

ConstructorInfoEx? constructor;
IServiceProviderIsService? serviceProviderIsService = provider.GetService<IServiceProviderIsService>();
// if container supports using IServiceProviderIsService, we try to find the longest ctor that
// (a) matches all parameters given to CreateInstance
Expand All@@ -61,10 +85,11 @@ public static object CreateInstance(
ConstructorMatcher bestMatcher = default;
bool multipleBestLengthFound = false;

foreach (ConstructorInfo? constructor in instanceType.GetConstructors())
for (int i = 0; i < constructors.Length; i++)
{
var matcher = new ConstructorMatcher(constructor);
bool isPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false);
constructor = constructors[i];
ConstructorMatcher matcher = new(constructor);
bool isPreferred = constructor.IsPreferred;
int length = matcher.Match(parameters, serviceProviderIsService);

if (isPreferred)
Expand DownExpand Up@@ -105,18 +130,79 @@ public static object CreateInstance(
}
}

Type?[] argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
Type?[] argumentTypes;
if (parameters.Length == 0)
{
argumentTypes[i] = parameters[i]?.GetType();
argumentTypes = Type.EmptyTypes;
}
else
{
argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
{
argumentTypes[i] = parameters[i]?.GetType();
}
}

FindApplicableConstructor(instanceType, argumentTypes, out ConstructorInfo constructorInfo, out int?[] parameterMap);
var constructorMatcher = new ConstructorMatcher(constructorInfo);

// Find the ConstructorInfoEx from the given constructorInfo.
constructor = null;
foreach (ConstructorInfoEx ctor in constructors)
Comment thread
steveharter marked this conversation as resolved.
{
if (ReferenceEquals(ctor.Info, constructorInfo))
{
constructor = ctor;
break;
}
}

Debug.Assert(constructor != null);

var constructorMatcher = new ConstructorMatcher(constructor);
constructorMatcher.MapParameters(parameterMap, parameters);
return constructorMatcher.CreateInstance(provider);
}

#if NETCOREAPP
private static ConstructorInfoEx[] GetOrAddConstructors(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
// Not found. Do the slower work of checking for the value in the correct cache.
// Null and non-collectible load contexts use the default cache.
if (!type.Assembly.IsCollectible)
{
return s_constructorInfos.GetOrAdd(type, CreateConstructorInfoExs(type));
}

// Collectible load contexts should use the ConditionalWeakTable so they can be unloaded.
if (s_collectibleConstructorInfos.Value.TryGetValue(type, out ConstructorInfoEx[]? value))
{
return value;
}

value = CreateConstructorInfoExs(type);

// ConditionalWeakTable doesn't support GetOrAdd() so use AddOrUpdate(). This means threads
// can have different instances for the same type, but that is OK since they are equivalent.
s_collectibleConstructorInfos.Value.AddOrUpdate(type, value);
return value;
}
#endif // NETCOREAPP

private static ConstructorInfoEx[] CreateConstructorInfoExs(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
ConstructorInfo[] constructors = type.GetConstructors();
ConstructorInfoEx[]? value = new ConstructorInfoEx[constructors.Length];
for (int i = 0; i < constructors.Length; i++)
{
value[i] = new ConstructorInfoEx(constructors[i]);
}

return value;
}

/// <summary>
/// Create a delegate that will instantiate a type with constructor arguments provided directly
/// and/or from an <see cref="IServiceProvider"/>.
Expand DownExpand Up@@ -551,58 +637,82 @@ private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters,
return true;
}

private static object? GetService(IServiceProvider serviceProvider, ParameterInfo parameterInfo)
private sealed class ConstructorInfoEx
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public readonly ConstructorInfo Info;
public readonly ParameterInfo[] Parameters;
public readonly bool IsPreferred;
private readonly object?[]? _parameterKeys;

public ConstructorInfoEx(ConstructorInfo constructor)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
Info = constructor;
Parameters = constructor.GetParameters();
IsPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false);

for (int i = 0; i < Parameters.Length; i++)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
FromKeyedServicesAttribute? attr = (FromKeyedServicesAttribute?)
Attribute.GetCustomAttribute(Parameters[i], typeof(FromKeyedServicesAttribute), inherit: false);

if (attr is not null)
{
_parameterKeys ??= new object?[Parameters.Length];
_parameterKeys[i] = attr.Key;
}
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
// Try non keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}

private static bool IsService(IServiceProviderIsService serviceProviderIsService, ParameterInfo parameterInfo)
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public bool IsService(IServiceProviderIsService serviceProviderIsService, int parameterIndex)
{
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);

// Use non-keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}
// Try non keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}

private static bool TryGetServiceKey(ParameterInfo parameterInfo, out object? key)
{
foreach (var attribute in parameterInfo.GetCustomAttributes<FromKeyedServicesAttribute>(false))
public object? GetService(IServiceProvider serviceProvider, int parameterIndex)
{
key = attribute.Key;
return true;
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}

// Use non-keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}
key = null;
return false;
}

private readonly struct ConstructorMatcher
{
private readonly ConstructorInfo _constructor;
private readonly ParameterInfo[] _parameters;
private readonly ConstructorInfoEx _constructor;
private readonly object?[] _parameterValues;

public ConstructorMatcher(ConstructorInfo constructor)
public ConstructorMatcher(ConstructorInfoEx constructor)
{
_constructor = constructor;
_parameters = _constructor.GetParameters();
_parameterValues = new object?[_parameters.Length];
_parameterValues = new object[constructor.Parameters.Length];
}

public int Match(object[] givenParameters, IServiceProviderIsService serviceProviderIsService)
Expand All@@ -612,10 +722,10 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
Type? givenType = givenParameters[givenIndex]?.GetType();
bool givenMatched = false;

for (int applyIndex = 0; applyIndex < _parameters.Length; applyIndex++)
for (int applyIndex = 0; applyIndex < _constructor.Parameters.Length; applyIndex++)
{
if (_parameterValues[applyIndex] == null &&
_parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
_constructor.Parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
{
givenMatched = true;
_parameterValues[applyIndex] = givenParameters[givenIndex];
Expand All@@ -630,12 +740,12 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}

// confirms the rest of ctor arguments match either as a parameter with a default value or as a service registered
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (_parameterValues[i] == null &&
!IsService(serviceProviderIsService, _parameters[i]))
!_constructor.IsService(serviceProviderIsService, i))
{
if (ParameterDefaultValue.TryGetDefaultValue(_parameters[i], out object? defaultValue))
if (ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[i], out object? defaultValue))
{
_parameterValues[i] = defaultValue;
}
Expand All@@ -646,21 +756,21 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}
}

return _parameters.Length;
return _constructor.Parameters.Length;
}

public object CreateInstance(IServiceProvider provider)
{
for (int index = 0; index < _parameters.Length; index++)
for (int index = 0; index < _constructor.Parameters.Length; index++)
{
if (_parameterValues[index] == null)
{
object? value = GetService(provider, _parameters[index]);
object? value = _constructor.GetService(provider, index);
if (value == null)
{
if (!ParameterDefaultValue.TryGetDefaultValue(_parameters[index], out object? defaultValue))
if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[index], out object? defaultValue))
{
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _parameters[index].ParameterType, _constructor.DeclaringType));
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _constructor.Parameters[index].ParameterType, _constructor.Info.DeclaringType));
}
else
{
Expand All@@ -677,7 +787,7 @@ public object CreateInstance(IServiceProvider provider)
#if NETFRAMEWORK || NETSTANDARD2_0
try
{
return _constructor.Invoke(_parameterValues);
return _constructor.Info.Invoke(_parameterValues);
}
catch (TargetInvocationException ex) when (ex.InnerException != null)
{
Expand All@@ -686,13 +796,13 @@ public object CreateInstance(IServiceProvider provider)
throw;
}
#else
return _constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
return _constructor.Info.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
#endif
}

public void MapParameters(int?[] parameterMap, object[] givenParameters)
{
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (parameterMap[i] != null)
{
Expand DownExpand Up@@ -974,5 +1084,20 @@ private static object ReflectionFactoryCanonical(
return constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, constructorArguments, culture: null);
}
#endif // NET8_0_OR_GREATER

#if NETCOREAPP
internal static class ActivatorUtilitiesUpdateHandler
{
public static void ClearCache(Type[]? _)
{
// Ignore the Type[] argument; just clear the caches.
s_constructorInfos.Clear();
if (s_collectibleConstructorInfos.IsValueCreated)
{
s_collectibleConstructorInfos.Value.Clear();
}
}
}
#endif
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Extensions.DependencyInjection;

namespace CollectibleAssembly
{
public class ClassToCreate
{
public object ClassAsCtorArgument { get; set; }

public ClassToCreate(ClassAsCtorArgument obj) { ClassAsCtorArgument = obj; }

public static object Create(ServiceProvider provider)
{
// Both the type to create (ClassToCreate) and the ctor's arg type (ClassAsCtorArgument) are
// located in this assembly, so both types need to be GC'd for this assembly to be collected.
return ActivatorUtilities.CreateInstance<ClassToCreate>(provider, new ClassAsCtorArgument());
}
}

public class ClassAsCtorArgument
{
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
Expand All@@ -10,13 +11,25 @@
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.Internal;

#if NETCOREAPP
[assembly: System.Reflection.Metadata.MetadataUpdateHandler(typeof(Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ActivatorUtilitiesUpdateHandler))]
#endif

namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Helper code for the various activator services.
/// </summary>
public static class ActivatorUtilities
{
#if NETCOREAPP
// Support caching of constructor metadata for the common case of types in non-collectible assemblies.
private static readonly ConcurrentDictionary<Type, ConstructorInfoEx[]> s_constructorInfos = new();

// Support caching of constructor metadata for types in collectible assemblies.
private static readonly Lazy<ConditionalWeakTable<Type, ConstructorInfoEx[]>> s_collectibleConstructorInfos = new();
#endif

#if NET8_0_OR_GREATER
// Maximum number of fixed arguments for ConstructorInvoker.Invoke(arg1, etc).
private const int FixedArgumentThreshold = 4;
Expand DownExpand Up@@ -47,6 +60,17 @@ public static object CreateInstance(
throw new InvalidOperationException(SR.CannotCreateAbstractClasses);
}

ConstructorInfoEx[]? constructors;
#if NETCOREAPP
if (!s_constructorInfos.TryGetValue(instanceType, out constructors))
{
constructors = GetOrAddConstructors(instanceType);
}
#else
constructors = CreateConstructorInfoExs(instanceType);
#endif

ConstructorInfoEx? constructor;
IServiceProviderIsService? serviceProviderIsService = provider.GetService<IServiceProviderIsService>();
// if container supports using IServiceProviderIsService, we try to find the longest ctor that
// (a) matches all parameters given to CreateInstance
Expand All@@ -61,10 +85,11 @@ public static object CreateInstance(
ConstructorMatcher bestMatcher = default;
bool multipleBestLengthFound = false;

foreach (ConstructorInfo? constructor in instanceType.GetConstructors())
for (int i = 0; i < constructors.Length; i++)
{
var matcher = new ConstructorMatcher(constructor);
bool isPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false);
constructor = constructors[i];
ConstructorMatcher matcher = new(constructor);
bool isPreferred = constructor.IsPreferred;
int length = matcher.Match(parameters, serviceProviderIsService);

if (isPreferred)
Expand DownExpand Up@@ -105,18 +130,79 @@ public static object CreateInstance(
}
}

Type?[] argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
Type?[] argumentTypes;
if (parameters.Length == 0)
{
argumentTypes[i] = parameters[i]?.GetType();
argumentTypes = Type.EmptyTypes;
}
else
{
argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
{
argumentTypes[i] = parameters[i]?.GetType();
}
}

FindApplicableConstructor(instanceType, argumentTypes, out ConstructorInfo constructorInfo, out int?[] parameterMap);
var constructorMatcher = new ConstructorMatcher(constructorInfo);

// Find the ConstructorInfoEx from the given constructorInfo.
constructor = null;
foreach (ConstructorInfoEx ctor in constructors)
Comment thread
steveharter marked this conversation as resolved.
{
if (ReferenceEquals(ctor.Info, constructorInfo))
{
constructor = ctor;
break;
}
}

Debug.Assert(constructor != null);

var constructorMatcher = new ConstructorMatcher(constructor);
constructorMatcher.MapParameters(parameterMap, parameters);
return constructorMatcher.CreateInstance(provider);
}

#if NETCOREAPP
private static ConstructorInfoEx[] GetOrAddConstructors(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
// Not found. Do the slower work of checking for the value in the correct cache.
// Null and non-collectible load contexts use the default cache.
if (!type.Assembly.IsCollectible)
{
return s_constructorInfos.GetOrAdd(type, CreateConstructorInfoExs(type));
}

// Collectible load contexts should use the ConditionalWeakTable so they can be unloaded.
if (s_collectibleConstructorInfos.Value.TryGetValue(type, out ConstructorInfoEx[]? value))
{
return value;
}

value = CreateConstructorInfoExs(type);

// ConditionalWeakTable doesn't support GetOrAdd() so use AddOrUpdate(). This means threads
// can have different instances for the same type, but that is OK since they are equivalent.
s_collectibleConstructorInfos.Value.AddOrUpdate(type, value);
return value;
}
#endif // NETCOREAPP

private static ConstructorInfoEx[] CreateConstructorInfoExs(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
ConstructorInfo[] constructors = type.GetConstructors();
ConstructorInfoEx[]? value = new ConstructorInfoEx[constructors.Length];
for (int i = 0; i < constructors.Length; i++)
{
value[i] = new ConstructorInfoEx(constructors[i]);
}

return value;
}

/// <summary>
/// Create a delegate that will instantiate a type with constructor arguments provided directly
/// and/or from an <see cref="IServiceProvider"/>.
Expand DownExpand Up@@ -551,58 +637,82 @@ private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters,
return true;
}

private static object? GetService(IServiceProvider serviceProvider, ParameterInfo parameterInfo)
private sealed class ConstructorInfoEx
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public readonly ConstructorInfo Info;
public readonly ParameterInfo[] Parameters;
public readonly bool IsPreferred;
private readonly object?[]? _parameterKeys;

public ConstructorInfoEx(ConstructorInfo constructor)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
Info = constructor;
Parameters = constructor.GetParameters();
IsPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false);

for (int i = 0; i < Parameters.Length; i++)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
FromKeyedServicesAttribute? attr = (FromKeyedServicesAttribute?)
Attribute.GetCustomAttribute(Parameters[i], typeof(FromKeyedServicesAttribute), inherit: false);

if (attr is not null)
{
_parameterKeys ??= new object?[Parameters.Length];
_parameterKeys[i] = attr.Key;
}
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
// Try non keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}

private static bool IsService(IServiceProviderIsService serviceProviderIsService, ParameterInfo parameterInfo)
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public bool IsService(IServiceProviderIsService serviceProviderIsService, int parameterIndex)
{
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);

// Use non-keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}
// Try non keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}

private static bool TryGetServiceKey(ParameterInfo parameterInfo, out object? key)
{
foreach (var attribute in parameterInfo.GetCustomAttributes<FromKeyedServicesAttribute>(false))
public object? GetService(IServiceProvider serviceProvider, int parameterIndex)
{
key = attribute.Key;
return true;
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}

// Use non-keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}
key = null;
return false;
}

private readonly struct ConstructorMatcher
{
private readonly ConstructorInfo _constructor;
private readonly ParameterInfo[] _parameters;
private readonly ConstructorInfoEx _constructor;
private readonly object?[] _parameterValues;

public ConstructorMatcher(ConstructorInfo constructor)
public ConstructorMatcher(ConstructorInfoEx constructor)
{
_constructor = constructor;
_parameters = _constructor.GetParameters();
_parameterValues = new object?[_parameters.Length];
_parameterValues = new object[constructor.Parameters.Length];
}

public int Match(object[] givenParameters, IServiceProviderIsService serviceProviderIsService)
Expand All@@ -612,10 +722,10 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
Type? givenType = givenParameters[givenIndex]?.GetType();
bool givenMatched = false;

for (int applyIndex = 0; applyIndex < _parameters.Length; applyIndex++)
for (int applyIndex = 0; applyIndex < _constructor.Parameters.Length; applyIndex++)
{
if (_parameterValues[applyIndex] == null &&
_parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
_constructor.Parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
{
givenMatched = true;
_parameterValues[applyIndex] = givenParameters[givenIndex];
Expand All@@ -630,12 +740,12 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}

// confirms the rest of ctor arguments match either as a parameter with a default value or as a service registered
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (_parameterValues[i] == null &&
!IsService(serviceProviderIsService, _parameters[i]))
!_constructor.IsService(serviceProviderIsService, i))
{
if (ParameterDefaultValue.TryGetDefaultValue(_parameters[i], out object? defaultValue))
if (ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[i], out object? defaultValue))
{
_parameterValues[i] = defaultValue;
}
Expand All@@ -646,21 +756,21 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}
}

return _parameters.Length;
return _constructor.Parameters.Length;
}

public object CreateInstance(IServiceProvider provider)
{
for (int index = 0; index < _parameters.Length; index++)
for (int index = 0; index < _constructor.Parameters.Length; index++)
{
if (_parameterValues[index] == null)
{
object? value = GetService(provider, _parameters[index]);
object? value = _constructor.GetService(provider, index);
if (value == null)
{
if (!ParameterDefaultValue.TryGetDefaultValue(_parameters[index], out object? defaultValue))
if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[index], out object? defaultValue))
{
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _parameters[index].ParameterType, _constructor.DeclaringType));
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _constructor.Parameters[index].ParameterType, _constructor.Info.DeclaringType));
}
else
{
Expand All@@ -677,7 +787,7 @@ public object CreateInstance(IServiceProvider provider)
#if NETFRAMEWORK || NETSTANDARD2_0
try
{
return _constructor.Invoke(_parameterValues);
return _constructor.Info.Invoke(_parameterValues);
}
catch (TargetInvocationException ex) when (ex.InnerException != null)
{
Expand All@@ -686,13 +796,13 @@ public object CreateInstance(IServiceProvider provider)
throw;
}
#else
return _constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
return _constructor.Info.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
#endif
}

public void MapParameters(int?[] parameterMap, object[] givenParameters)
{
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (parameterMap[i] != null)
{
Expand DownExpand Up@@ -974,5 +1084,20 @@ private static object ReflectionFactoryCanonical(
return constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, constructorArguments, culture: null);
}
#endif // NET8_0_OR_GREATER

#if NETCOREAPP
internal static class ActivatorUtilitiesUpdateHandler
{
public static void ClearCache(Type[]? _)
{
// Ignore the Type[] argument; just clear the caches.
s_constructorInfos.Clear();
if (s_collectibleConstructorInfos.IsValueCreated)
{
s_collectibleConstructorInfos.Value.Clear();
}
}
}
#endif
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Extensions.DependencyInjection;

namespace CollectibleAssembly
{
public class ClassToCreate
{
public object ClassAsCtorArgument { get; set; }

public ClassToCreate(ClassAsCtorArgument obj) { ClassAsCtorArgument = obj; }

public static object Create(ServiceProvider provider)
{
// Both the type to create (ClassToCreate) and the ctor's arg type (ClassAsCtorArgument) are
// located in this assembly, so both types need to be GC'd for this assembly to be collected.
return ActivatorUtilities.CreateInstance<ClassToCreate>(provider, new ClassAsCtorArgument());
}
}

public class ClassAsCtorArgument
{
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
Expand All@@ -10,13 +11,25 @@
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.Internal;

#if NETCOREAPP
[assembly: System.Reflection.Metadata.MetadataUpdateHandler(typeof(Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ActivatorUtilitiesUpdateHandler))]
#endif

namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Helper code for the various activator services.
/// </summary>
public static class ActivatorUtilities
{
#if NETCOREAPP
// Support caching of constructor metadata for the common case of types in non-collectible assemblies.
private static readonly ConcurrentDictionary<Type, ConstructorInfoEx[]> s_constructorInfos = new();

// Support caching of constructor metadata for types in collectible assemblies.
private static readonly Lazy<ConditionalWeakTable<Type, ConstructorInfoEx[]>> s_collectibleConstructorInfos = new();
#endif

#if NET8_0_OR_GREATER
// Maximum number of fixed arguments for ConstructorInvoker.Invoke(arg1, etc).
private const int FixedArgumentThreshold = 4;
Expand DownExpand Up@@ -47,6 +60,17 @@ public static object CreateInstance(
throw new InvalidOperationException(SR.CannotCreateAbstractClasses);
}

ConstructorInfoEx[]? constructors;
#if NETCOREAPP
if (!s_constructorInfos.TryGetValue(instanceType, out constructors))
{
constructors = GetOrAddConstructors(instanceType);
}
#else
constructors = CreateConstructorInfoExs(instanceType);
#endif

ConstructorInfoEx? constructor;
IServiceProviderIsService? serviceProviderIsService = provider.GetService<IServiceProviderIsService>();
// if container supports using IServiceProviderIsService, we try to find the longest ctor that
// (a) matches all parameters given to CreateInstance
Expand All@@ -61,10 +85,11 @@ public static object CreateInstance(
ConstructorMatcher bestMatcher = default;
bool multipleBestLengthFound = false;

foreach (ConstructorInfo? constructor in instanceType.GetConstructors())
for (int i = 0; i < constructors.Length; i++)
{
var matcher = new ConstructorMatcher(constructor);
bool isPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false);
constructor = constructors[i];
ConstructorMatcher matcher = new(constructor);
bool isPreferred = constructor.IsPreferred;
int length = matcher.Match(parameters, serviceProviderIsService);

if (isPreferred)
Expand DownExpand Up@@ -105,18 +130,79 @@ public static object CreateInstance(
}
}

Type?[] argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
Type?[] argumentTypes;
if (parameters.Length == 0)
{
argumentTypes[i] = parameters[i]?.GetType();
argumentTypes = Type.EmptyTypes;
}
else
{
argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
{
argumentTypes[i] = parameters[i]?.GetType();
}
}

FindApplicableConstructor(instanceType, argumentTypes, out ConstructorInfo constructorInfo, out int?[] parameterMap);
var constructorMatcher = new ConstructorMatcher(constructorInfo);

// Find the ConstructorInfoEx from the given constructorInfo.
constructor = null;
foreach (ConstructorInfoEx ctor in constructors)
Comment thread
steveharter marked this conversation as resolved.
{
if (ReferenceEquals(ctor.Info, constructorInfo))
{
constructor = ctor;
break;
}
}

Debug.Assert(constructor != null);

var constructorMatcher = new ConstructorMatcher(constructor);
constructorMatcher.MapParameters(parameterMap, parameters);
return constructorMatcher.CreateInstance(provider);
}

#if NETCOREAPP
private static ConstructorInfoEx[] GetOrAddConstructors(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
// Not found. Do the slower work of checking for the value in the correct cache.
// Null and non-collectible load contexts use the default cache.
if (!type.Assembly.IsCollectible)
{
return s_constructorInfos.GetOrAdd(type, CreateConstructorInfoExs(type));
}

// Collectible load contexts should use the ConditionalWeakTable so they can be unloaded.
if (s_collectibleConstructorInfos.Value.TryGetValue(type, out ConstructorInfoEx[]? value))
{
return value;
}

value = CreateConstructorInfoExs(type);

// ConditionalWeakTable doesn't support GetOrAdd() so use AddOrUpdate(). This means threads
// can have different instances for the same type, but that is OK since they are equivalent.
s_collectibleConstructorInfos.Value.AddOrUpdate(type, value);
return value;
}
#endif // NETCOREAPP

private static ConstructorInfoEx[] CreateConstructorInfoExs(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
ConstructorInfo[] constructors = type.GetConstructors();
ConstructorInfoEx[]? value = new ConstructorInfoEx[constructors.Length];
for (int i = 0; i < constructors.Length; i++)
{
value[i] = new ConstructorInfoEx(constructors[i]);
}

return value;
}

/// <summary>
/// Create a delegate that will instantiate a type with constructor arguments provided directly
/// and/or from an <see cref="IServiceProvider"/>.
Expand DownExpand Up@@ -551,58 +637,82 @@ private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters,
return true;
}

private static object? GetService(IServiceProvider serviceProvider, ParameterInfo parameterInfo)
private sealed class ConstructorInfoEx
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public readonly ConstructorInfo Info;
public readonly ParameterInfo[] Parameters;
public readonly bool IsPreferred;
private readonly object?[]? _parameterKeys;

public ConstructorInfoEx(ConstructorInfo constructor)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
Info = constructor;
Parameters = constructor.GetParameters();
IsPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false);

for (int i = 0; i < Parameters.Length; i++)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
FromKeyedServicesAttribute? attr = (FromKeyedServicesAttribute?)
Attribute.GetCustomAttribute(Parameters[i], typeof(FromKeyedServicesAttribute), inherit: false);

if (attr is not null)
{
_parameterKeys ??= new object?[Parameters.Length];
_parameterKeys[i] = attr.Key;
}
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
// Try non keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}

private static bool IsService(IServiceProviderIsService serviceProviderIsService, ParameterInfo parameterInfo)
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public bool IsService(IServiceProviderIsService serviceProviderIsService, int parameterIndex)
{
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);

// Use non-keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}
// Try non keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}

private static bool TryGetServiceKey(ParameterInfo parameterInfo, out object? key)
{
foreach (var attribute in parameterInfo.GetCustomAttributes<FromKeyedServicesAttribute>(false))
public object? GetService(IServiceProvider serviceProvider, int parameterIndex)
{
key = attribute.Key;
return true;
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}

// Use non-keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}
key = null;
return false;
}

private readonly struct ConstructorMatcher
{
private readonly ConstructorInfo _constructor;
private readonly ParameterInfo[] _parameters;
private readonly ConstructorInfoEx _constructor;
private readonly object?[] _parameterValues;

public ConstructorMatcher(ConstructorInfo constructor)
public ConstructorMatcher(ConstructorInfoEx constructor)
{
_constructor = constructor;
_parameters = _constructor.GetParameters();
_parameterValues = new object?[_parameters.Length];
_parameterValues = new object[constructor.Parameters.Length];
}

public int Match(object[] givenParameters, IServiceProviderIsService serviceProviderIsService)
Expand All@@ -612,10 +722,10 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
Type? givenType = givenParameters[givenIndex]?.GetType();
bool givenMatched = false;

for (int applyIndex = 0; applyIndex < _parameters.Length; applyIndex++)
for (int applyIndex = 0; applyIndex < _constructor.Parameters.Length; applyIndex++)
{
if (_parameterValues[applyIndex] == null &&
_parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
_constructor.Parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
{
givenMatched = true;
_parameterValues[applyIndex] = givenParameters[givenIndex];
Expand All@@ -630,12 +740,12 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}

// confirms the rest of ctor arguments match either as a parameter with a default value or as a service registered
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (_parameterValues[i] == null &&
!IsService(serviceProviderIsService, _parameters[i]))
!_constructor.IsService(serviceProviderIsService, i))
{
if (ParameterDefaultValue.TryGetDefaultValue(_parameters[i], out object? defaultValue))
if (ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[i], out object? defaultValue))
{
_parameterValues[i] = defaultValue;
}
Expand All@@ -646,21 +756,21 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}
}

return _parameters.Length;
return _constructor.Parameters.Length;
}

public object CreateInstance(IServiceProvider provider)
{
for (int index = 0; index < _parameters.Length; index++)
for (int index = 0; index < _constructor.Parameters.Length; index++)
{
if (_parameterValues[index] == null)
{
object? value = GetService(provider, _parameters[index]);
object? value = _constructor.GetService(provider, index);
if (value == null)
{
if (!ParameterDefaultValue.TryGetDefaultValue(_parameters[index], out object? defaultValue))
if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[index], out object? defaultValue))
{
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _parameters[index].ParameterType, _constructor.DeclaringType));
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _constructor.Parameters[index].ParameterType, _constructor.Info.DeclaringType));
}
else
{
Expand All@@ -677,7 +787,7 @@ public object CreateInstance(IServiceProvider provider)
#if NETFRAMEWORK || NETSTANDARD2_0
try
{
return _constructor.Invoke(_parameterValues);
return _constructor.Info.Invoke(_parameterValues);
}
catch (TargetInvocationException ex) when (ex.InnerException != null)
{
Expand All@@ -686,13 +796,13 @@ public object CreateInstance(IServiceProvider provider)
throw;
}
#else
return _constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
return _constructor.Info.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
#endif
}

public void MapParameters(int?[] parameterMap, object[] givenParameters)
{
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (parameterMap[i] != null)
{
Expand DownExpand Up@@ -974,5 +1084,20 @@ private static object ReflectionFactoryCanonical(
return constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, constructorArguments, culture: null);
}
#endif // NET8_0_OR_GREATER

#if NETCOREAPP
internal static class ActivatorUtilitiesUpdateHandler
{
public static void ClearCache(Type[]? _)
{
// Ignore the Type[] argument; just clear the caches.
s_constructorInfos.Clear();
if (s_collectibleConstructorInfos.IsValueCreated)
{
s_collectibleConstructorInfos.Value.Clear();
}
}
}
#endif
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Extensions.DependencyInjection;

namespace CollectibleAssembly
{
public class ClassToCreate
{
public object ClassAsCtorArgument { get; set; }

public ClassToCreate(ClassAsCtorArgument obj) { ClassAsCtorArgument = obj; }

public static object Create(ServiceProvider provider)
{
// Both the type to create (ClassToCreate) and the ctor's arg type (ClassAsCtorArgument) are
// located in this assembly, so both types need to be GC'd for this assembly to be collected.
return ActivatorUtilities.CreateInstance<ClassToCreate>(provider, new ClassAsCtorArgument());
}
}

public class ClassAsCtorArgument
{
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
Expand All@@ -10,13 +11,25 @@
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.Internal;

#if NETCOREAPP
[assembly: System.Reflection.Metadata.MetadataUpdateHandler(typeof(Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ActivatorUtilitiesUpdateHandler))]
#endif

namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Helper code for the various activator services.
/// </summary>
public static class ActivatorUtilities
{
#if NETCOREAPP
// Support caching of constructor metadata for the common case of types in non-collectible assemblies.
private static readonly ConcurrentDictionary<Type, ConstructorInfoEx[]> s_constructorInfos = new();

// Support caching of constructor metadata for types in collectible assemblies.
private static readonly Lazy<ConditionalWeakTable<Type, ConstructorInfoEx[]>> s_collectibleConstructorInfos = new();
#endif

#if NET8_0_OR_GREATER
// Maximum number of fixed arguments for ConstructorInvoker.Invoke(arg1, etc).
private const int FixedArgumentThreshold = 4;
Expand DownExpand Up@@ -47,6 +60,17 @@ public static object CreateInstance(
throw new InvalidOperationException(SR.CannotCreateAbstractClasses);
}

ConstructorInfoEx[]? constructors;
#if NETCOREAPP
if (!s_constructorInfos.TryGetValue(instanceType, out constructors))
{
constructors = GetOrAddConstructors(instanceType);
}
#else
constructors = CreateConstructorInfoExs(instanceType);
#endif

ConstructorInfoEx? constructor;
IServiceProviderIsService? serviceProviderIsService = provider.GetService<IServiceProviderIsService>();
// if container supports using IServiceProviderIsService, we try to find the longest ctor that
// (a) matches all parameters given to CreateInstance
Expand All@@ -61,10 +85,11 @@ public static object CreateInstance(
ConstructorMatcher bestMatcher = default;
bool multipleBestLengthFound = false;

foreach (ConstructorInfo? constructor in instanceType.GetConstructors())
for (int i = 0; i < constructors.Length; i++)
{
var matcher = new ConstructorMatcher(constructor);
bool isPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false);
constructor = constructors[i];
ConstructorMatcher matcher = new(constructor);
bool isPreferred = constructor.IsPreferred;
int length = matcher.Match(parameters, serviceProviderIsService);

if (isPreferred)
Expand DownExpand Up@@ -105,18 +130,79 @@ public static object CreateInstance(
}
}

Type?[] argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
Type?[] argumentTypes;
if (parameters.Length == 0)
{
argumentTypes[i] = parameters[i]?.GetType();
argumentTypes = Type.EmptyTypes;
}
else
{
argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
{
argumentTypes[i] = parameters[i]?.GetType();
}
}

FindApplicableConstructor(instanceType, argumentTypes, out ConstructorInfo constructorInfo, out int?[] parameterMap);
var constructorMatcher = new ConstructorMatcher(constructorInfo);

// Find the ConstructorInfoEx from the given constructorInfo.
constructor = null;
foreach (ConstructorInfoEx ctor in constructors)
Comment thread
steveharter marked this conversation as resolved.
{
if (ReferenceEquals(ctor.Info, constructorInfo))
{
constructor = ctor;
break;
}
}

Debug.Assert(constructor != null);

var constructorMatcher = new ConstructorMatcher(constructor);
constructorMatcher.MapParameters(parameterMap, parameters);
return constructorMatcher.CreateInstance(provider);
}

#if NETCOREAPP
private static ConstructorInfoEx[] GetOrAddConstructors(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
// Not found. Do the slower work of checking for the value in the correct cache.
// Null and non-collectible load contexts use the default cache.
if (!type.Assembly.IsCollectible)
{
return s_constructorInfos.GetOrAdd(type, CreateConstructorInfoExs(type));
}

// Collectible load contexts should use the ConditionalWeakTable so they can be unloaded.
if (s_collectibleConstructorInfos.Value.TryGetValue(type, out ConstructorInfoEx[]? value))
{
return value;
}

value = CreateConstructorInfoExs(type);

// ConditionalWeakTable doesn't support GetOrAdd() so use AddOrUpdate(). This means threads
// can have different instances for the same type, but that is OK since they are equivalent.
s_collectibleConstructorInfos.Value.AddOrUpdate(type, value);
return value;
}
#endif // NETCOREAPP

private static ConstructorInfoEx[] CreateConstructorInfoExs(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
ConstructorInfo[] constructors = type.GetConstructors();
ConstructorInfoEx[]? value = new ConstructorInfoEx[constructors.Length];
for (int i = 0; i < constructors.Length; i++)
{
value[i] = new ConstructorInfoEx(constructors[i]);
}

return value;
}

/// <summary>
/// Create a delegate that will instantiate a type with constructor arguments provided directly
/// and/or from an <see cref="IServiceProvider"/>.
Expand DownExpand Up@@ -551,58 +637,82 @@ private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters,
return true;
}

private static object? GetService(IServiceProvider serviceProvider, ParameterInfo parameterInfo)
private sealed class ConstructorInfoEx
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public readonly ConstructorInfo Info;
public readonly ParameterInfo[] Parameters;
public readonly bool IsPreferred;
private readonly object?[]? _parameterKeys;

public ConstructorInfoEx(ConstructorInfo constructor)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
Info = constructor;
Parameters = constructor.GetParameters();
IsPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false);

for (int i = 0; i < Parameters.Length; i++)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
FromKeyedServicesAttribute? attr = (FromKeyedServicesAttribute?)
Attribute.GetCustomAttribute(Parameters[i], typeof(FromKeyedServicesAttribute), inherit: false);

if (attr is not null)
{
_parameterKeys ??= new object?[Parameters.Length];
_parameterKeys[i] = attr.Key;
}
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
// Try non keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}

private static bool IsService(IServiceProviderIsService serviceProviderIsService, ParameterInfo parameterInfo)
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public bool IsService(IServiceProviderIsService serviceProviderIsService, int parameterIndex)
{
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);

// Use non-keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}
// Try non keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}

private static bool TryGetServiceKey(ParameterInfo parameterInfo, out object? key)
{
foreach (var attribute in parameterInfo.GetCustomAttributes<FromKeyedServicesAttribute>(false))
public object? GetService(IServiceProvider serviceProvider, int parameterIndex)
{
key = attribute.Key;
return true;
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}

// Use non-keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}
key = null;
return false;
}

private readonly struct ConstructorMatcher
{
private readonly ConstructorInfo _constructor;
private readonly ParameterInfo[] _parameters;
private readonly ConstructorInfoEx _constructor;
private readonly object?[] _parameterValues;

public ConstructorMatcher(ConstructorInfo constructor)
public ConstructorMatcher(ConstructorInfoEx constructor)
{
_constructor = constructor;
_parameters = _constructor.GetParameters();
_parameterValues = new object?[_parameters.Length];
_parameterValues = new object[constructor.Parameters.Length];
}

public int Match(object[] givenParameters, IServiceProviderIsService serviceProviderIsService)
Expand All@@ -612,10 +722,10 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
Type? givenType = givenParameters[givenIndex]?.GetType();
bool givenMatched = false;

for (int applyIndex = 0; applyIndex < _parameters.Length; applyIndex++)
for (int applyIndex = 0; applyIndex < _constructor.Parameters.Length; applyIndex++)
{
if (_parameterValues[applyIndex] == null &&
_parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
_constructor.Parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
{
givenMatched = true;
_parameterValues[applyIndex] = givenParameters[givenIndex];
Expand All@@ -630,12 +740,12 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}

// confirms the rest of ctor arguments match either as a parameter with a default value or as a service registered
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (_parameterValues[i] == null &&
!IsService(serviceProviderIsService, _parameters[i]))
!_constructor.IsService(serviceProviderIsService, i))
{
if (ParameterDefaultValue.TryGetDefaultValue(_parameters[i], out object? defaultValue))
if (ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[i], out object? defaultValue))
{
_parameterValues[i] = defaultValue;
}
Expand All@@ -646,21 +756,21 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}
}

return _parameters.Length;
return _constructor.Parameters.Length;
}

public object CreateInstance(IServiceProvider provider)
{
for (int index = 0; index < _parameters.Length; index++)
for (int index = 0; index < _constructor.Parameters.Length; index++)
{
if (_parameterValues[index] == null)
{
object? value = GetService(provider, _parameters[index]);
object? value = _constructor.GetService(provider, index);
if (value == null)
{
if (!ParameterDefaultValue.TryGetDefaultValue(_parameters[index], out object? defaultValue))
if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[index], out object? defaultValue))
{
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _parameters[index].ParameterType, _constructor.DeclaringType));
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _constructor.Parameters[index].ParameterType, _constructor.Info.DeclaringType));
}
else
{
Expand All@@ -677,7 +787,7 @@ public object CreateInstance(IServiceProvider provider)
#if NETFRAMEWORK || NETSTANDARD2_0
try
{
return _constructor.Invoke(_parameterValues);
return _constructor.Info.Invoke(_parameterValues);
}
catch (TargetInvocationException ex) when (ex.InnerException != null)
{
Expand All@@ -686,13 +796,13 @@ public object CreateInstance(IServiceProvider provider)
throw;
}
#else
return _constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
return _constructor.Info.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
#endif
}

public void MapParameters(int?[] parameterMap, object[] givenParameters)
{
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (parameterMap[i] != null)
{
Expand DownExpand Up@@ -974,5 +1084,20 @@ private static object ReflectionFactoryCanonical(
return constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, constructorArguments, culture: null);
}
#endif // NET8_0_OR_GREATER

#if NETCOREAPP
internal static class ActivatorUtilitiesUpdateHandler
{
public static void ClearCache(Type[]? _)
{
// Ignore the Type[] argument; just clear the caches.
s_constructorInfos.Clear();
if (s_collectibleConstructorInfos.IsValueCreated)
{
s_collectibleConstructorInfos.Value.Clear();
}
}
}
#endif
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Extensions.DependencyInjection;

namespace CollectibleAssembly
{
public class ClassToCreate
{
public object ClassAsCtorArgument { get; set; }

public ClassToCreate(ClassAsCtorArgument obj) { ClassAsCtorArgument = obj; }

public static object Create(ServiceProvider provider)
{
// Both the type to create (ClassToCreate) and the ctor's arg type (ClassAsCtorArgument) are
// located in this assembly, so both types need to be GC'd for this assembly to be collected.
return ActivatorUtilities.CreateInstance<ClassToCreate>(provider, new ClassAsCtorArgument());
}
}

public class ClassAsCtorArgument
{
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
Expand All@@ -10,13 +11,25 @@
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.Internal;

#if NETCOREAPP
[assembly: System.Reflection.Metadata.MetadataUpdateHandler(typeof(Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ActivatorUtilitiesUpdateHandler))]
#endif

namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Helper code for the various activator services.
/// </summary>
public static class ActivatorUtilities
{
#if NETCOREAPP
// Support caching of constructor metadata for the common case of types in non-collectible assemblies.
private static readonly ConcurrentDictionary<Type, ConstructorInfoEx[]> s_constructorInfos = new();

// Support caching of constructor metadata for types in collectible assemblies.
private static readonly Lazy<ConditionalWeakTable<Type, ConstructorInfoEx[]>> s_collectibleConstructorInfos = new();
#endif

#if NET8_0_OR_GREATER
// Maximum number of fixed arguments for ConstructorInvoker.Invoke(arg1, etc).
private const int FixedArgumentThreshold = 4;
Expand DownExpand Up@@ -47,6 +60,17 @@ public static object CreateInstance(
throw new InvalidOperationException(SR.CannotCreateAbstractClasses);
}

ConstructorInfoEx[]? constructors;
#if NETCOREAPP
if (!s_constructorInfos.TryGetValue(instanceType, out constructors))
{
constructors = GetOrAddConstructors(instanceType);
}
#else
constructors = CreateConstructorInfoExs(instanceType);
#endif

ConstructorInfoEx? constructor;
IServiceProviderIsService? serviceProviderIsService = provider.GetService<IServiceProviderIsService>();
// if container supports using IServiceProviderIsService, we try to find the longest ctor that
// (a) matches all parameters given to CreateInstance
Expand All@@ -61,10 +85,11 @@ public static object CreateInstance(
ConstructorMatcher bestMatcher = default;
bool multipleBestLengthFound = false;

foreach (ConstructorInfo? constructor in instanceType.GetConstructors())
for (int i = 0; i < constructors.Length; i++)
{
var matcher = new ConstructorMatcher(constructor);
bool isPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false);
constructor = constructors[i];
ConstructorMatcher matcher = new(constructor);
bool isPreferred = constructor.IsPreferred;
int length = matcher.Match(parameters, serviceProviderIsService);

if (isPreferred)
Expand DownExpand Up@@ -105,18 +130,79 @@ public static object CreateInstance(
}
}

Type?[] argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
Type?[] argumentTypes;
if (parameters.Length == 0)
{
argumentTypes[i] = parameters[i]?.GetType();
argumentTypes = Type.EmptyTypes;
}
else
{
argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
{
argumentTypes[i] = parameters[i]?.GetType();
}
}

FindApplicableConstructor(instanceType, argumentTypes, out ConstructorInfo constructorInfo, out int?[] parameterMap);
var constructorMatcher = new ConstructorMatcher(constructorInfo);

// Find the ConstructorInfoEx from the given constructorInfo.
constructor = null;
foreach (ConstructorInfoEx ctor in constructors)
Comment thread
steveharter marked this conversation as resolved.
{
if (ReferenceEquals(ctor.Info, constructorInfo))
{
constructor = ctor;
break;
}
}

Debug.Assert(constructor != null);

var constructorMatcher = new ConstructorMatcher(constructor);
constructorMatcher.MapParameters(parameterMap, parameters);
return constructorMatcher.CreateInstance(provider);
}

#if NETCOREAPP
private static ConstructorInfoEx[] GetOrAddConstructors(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
// Not found. Do the slower work of checking for the value in the correct cache.
// Null and non-collectible load contexts use the default cache.
if (!type.Assembly.IsCollectible)
{
return s_constructorInfos.GetOrAdd(type, CreateConstructorInfoExs(type));
}

// Collectible load contexts should use the ConditionalWeakTable so they can be unloaded.
if (s_collectibleConstructorInfos.Value.TryGetValue(type, out ConstructorInfoEx[]? value))
{
return value;
}

value = CreateConstructorInfoExs(type);

// ConditionalWeakTable doesn't support GetOrAdd() so use AddOrUpdate(). This means threads
// can have different instances for the same type, but that is OK since they are equivalent.
s_collectibleConstructorInfos.Value.AddOrUpdate(type, value);
return value;
}
#endif // NETCOREAPP

private static ConstructorInfoEx[] CreateConstructorInfoExs(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
ConstructorInfo[] constructors = type.GetConstructors();
ConstructorInfoEx[]? value = new ConstructorInfoEx[constructors.Length];
for (int i = 0; i < constructors.Length; i++)
{
value[i] = new ConstructorInfoEx(constructors[i]);
}

return value;
}

/// <summary>
/// Create a delegate that will instantiate a type with constructor arguments provided directly
/// and/or from an <see cref="IServiceProvider"/>.
Expand DownExpand Up@@ -551,58 +637,82 @@ private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters,
return true;
}

private static object? GetService(IServiceProvider serviceProvider, ParameterInfo parameterInfo)
private sealed class ConstructorInfoEx
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public readonly ConstructorInfo Info;
public readonly ParameterInfo[] Parameters;
public readonly bool IsPreferred;
private readonly object?[]? _parameterKeys;

public ConstructorInfoEx(ConstructorInfo constructor)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
Info = constructor;
Parameters = constructor.GetParameters();
IsPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false);

for (int i = 0; i < Parameters.Length; i++)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
FromKeyedServicesAttribute? attr = (FromKeyedServicesAttribute?)
Attribute.GetCustomAttribute(Parameters[i], typeof(FromKeyedServicesAttribute), inherit: false);

if (attr is not null)
{
_parameterKeys ??= new object?[Parameters.Length];
_parameterKeys[i] = attr.Key;
}
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
// Try non keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}

private static bool IsService(IServiceProviderIsService serviceProviderIsService, ParameterInfo parameterInfo)
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public bool IsService(IServiceProviderIsService serviceProviderIsService, int parameterIndex)
{
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);

// Use non-keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}
// Try non keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}

private static bool TryGetServiceKey(ParameterInfo parameterInfo, out object? key)
{
foreach (var attribute in parameterInfo.GetCustomAttributes<FromKeyedServicesAttribute>(false))
public object? GetService(IServiceProvider serviceProvider, int parameterIndex)
{
key = attribute.Key;
return true;
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}

// Use non-keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}
key = null;
return false;
}

private readonly struct ConstructorMatcher
{
private readonly ConstructorInfo _constructor;
private readonly ParameterInfo[] _parameters;
private readonly ConstructorInfoEx _constructor;
private readonly object?[] _parameterValues;

public ConstructorMatcher(ConstructorInfo constructor)
public ConstructorMatcher(ConstructorInfoEx constructor)
{
_constructor = constructor;
_parameters = _constructor.GetParameters();
_parameterValues = new object?[_parameters.Length];
_parameterValues = new object[constructor.Parameters.Length];
}

public int Match(object[] givenParameters, IServiceProviderIsService serviceProviderIsService)
Expand All@@ -612,10 +722,10 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
Type? givenType = givenParameters[givenIndex]?.GetType();
bool givenMatched = false;

for (int applyIndex = 0; applyIndex < _parameters.Length; applyIndex++)
for (int applyIndex = 0; applyIndex < _constructor.Parameters.Length; applyIndex++)
{
if (_parameterValues[applyIndex] == null &&
_parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
_constructor.Parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
{
givenMatched = true;
_parameterValues[applyIndex] = givenParameters[givenIndex];
Expand All@@ -630,12 +740,12 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}

// confirms the rest of ctor arguments match either as a parameter with a default value or as a service registered
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (_parameterValues[i] == null &&
!IsService(serviceProviderIsService, _parameters[i]))
!_constructor.IsService(serviceProviderIsService, i))
{
if (ParameterDefaultValue.TryGetDefaultValue(_parameters[i], out object? defaultValue))
if (ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[i], out object? defaultValue))
{
_parameterValues[i] = defaultValue;
}
Expand All@@ -646,21 +756,21 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}
}

return _parameters.Length;
return _constructor.Parameters.Length;
}

public object CreateInstance(IServiceProvider provider)
{
for (int index = 0; index < _parameters.Length; index++)
for (int index = 0; index < _constructor.Parameters.Length; index++)
{
if (_parameterValues[index] == null)
{
object? value = GetService(provider, _parameters[index]);
object? value = _constructor.GetService(provider, index);
if (value == null)
{
if (!ParameterDefaultValue.TryGetDefaultValue(_parameters[index], out object? defaultValue))
if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[index], out object? defaultValue))
{
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _parameters[index].ParameterType, _constructor.DeclaringType));
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _constructor.Parameters[index].ParameterType, _constructor.Info.DeclaringType));
}
else
{
Expand All@@ -677,7 +787,7 @@ public object CreateInstance(IServiceProvider provider)
#if NETFRAMEWORK || NETSTANDARD2_0
try
{
return _constructor.Invoke(_parameterValues);
return _constructor.Info.Invoke(_parameterValues);
}
catch (TargetInvocationException ex) when (ex.InnerException != null)
{
Expand All@@ -686,13 +796,13 @@ public object CreateInstance(IServiceProvider provider)
throw;
}
#else
return _constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
return _constructor.Info.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
#endif
}

public void MapParameters(int?[] parameterMap, object[] givenParameters)
{
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (parameterMap[i] != null)
{
Expand DownExpand Up@@ -974,5 +1084,20 @@ private static object ReflectionFactoryCanonical(
return constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, constructorArguments, culture: null);
}
#endif // NET8_0_OR_GREATER

#if NETCOREAPP
internal static class ActivatorUtilitiesUpdateHandler
{
public static void ClearCache(Type[]? _)
{
// Ignore the Type[] argument; just clear the caches.
s_constructorInfos.Clear();
if (s_collectibleConstructorInfos.IsValueCreated)
{
s_collectibleConstructorInfos.Value.Clear();
}
}
}
#endif
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Extensions.DependencyInjection;

namespace CollectibleAssembly
{
public class ClassToCreate
{
public object ClassAsCtorArgument { get; set; }

public ClassToCreate(ClassAsCtorArgument obj) { ClassAsCtorArgument = obj; }

public static object Create(ServiceProvider provider)
{
// Both the type to create (ClassToCreate) and the ctor's arg type (ClassAsCtorArgument) are
// located in this assembly, so both types need to be GC'd for this assembly to be collected.
return ActivatorUtilities.CreateInstance<ClassToCreate>(provider, new ClassAsCtorArgument());
}
}

public class ClassAsCtorArgument
{
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
Expand All@@ -10,13 +11,25 @@
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.Internal;

#if NETCOREAPP
[assembly: System.Reflection.Metadata.MetadataUpdateHandler(typeof(Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ActivatorUtilitiesUpdateHandler))]
#endif

namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Helper code for the various activator services.
/// </summary>
public static class ActivatorUtilities
{
#if NETCOREAPP
// Support caching of constructor metadata for the common case of types in non-collectible assemblies.
private static readonly ConcurrentDictionary<Type, ConstructorInfoEx[]> s_constructorInfos = new();

// Support caching of constructor metadata for types in collectible assemblies.
private static readonly Lazy<ConditionalWeakTable<Type, ConstructorInfoEx[]>> s_collectibleConstructorInfos = new();
#endif

#if NET8_0_OR_GREATER
// Maximum number of fixed arguments for ConstructorInvoker.Invoke(arg1, etc).
private const int FixedArgumentThreshold = 4;
Expand DownExpand Up@@ -47,6 +60,17 @@ public static object CreateInstance(
throw new InvalidOperationException(SR.CannotCreateAbstractClasses);
}

ConstructorInfoEx[]? constructors;
#if NETCOREAPP
if (!s_constructorInfos.TryGetValue(instanceType, out constructors))
{
constructors = GetOrAddConstructors(instanceType);
}
#else
constructors = CreateConstructorInfoExs(instanceType);
#endif

ConstructorInfoEx? constructor;
IServiceProviderIsService? serviceProviderIsService = provider.GetService<IServiceProviderIsService>();
// if container supports using IServiceProviderIsService, we try to find the longest ctor that
// (a) matches all parameters given to CreateInstance
Expand All@@ -61,10 +85,11 @@ public static object CreateInstance(
ConstructorMatcher bestMatcher = default;
bool multipleBestLengthFound = false;

foreach (ConstructorInfo? constructor in instanceType.GetConstructors())
for (int i = 0; i < constructors.Length; i++)
{
var matcher = new ConstructorMatcher(constructor);
bool isPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false);
constructor = constructors[i];
ConstructorMatcher matcher = new(constructor);
bool isPreferred = constructor.IsPreferred;
int length = matcher.Match(parameters, serviceProviderIsService);

if (isPreferred)
Expand DownExpand Up@@ -105,18 +130,79 @@ public static object CreateInstance(
}
}

Type?[] argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
Type?[] argumentTypes;
if (parameters.Length == 0)
{
argumentTypes[i] = parameters[i]?.GetType();
argumentTypes = Type.EmptyTypes;
}
else
{
argumentTypes = new Type[parameters.Length];
for (int i = 0; i < argumentTypes.Length; i++)
{
argumentTypes[i] = parameters[i]?.GetType();
}
}

FindApplicableConstructor(instanceType, argumentTypes, out ConstructorInfo constructorInfo, out int?[] parameterMap);
var constructorMatcher = new ConstructorMatcher(constructorInfo);

// Find the ConstructorInfoEx from the given constructorInfo.
constructor = null;
foreach (ConstructorInfoEx ctor in constructors)
Comment thread
steveharter marked this conversation as resolved.
{
if (ReferenceEquals(ctor.Info, constructorInfo))
{
constructor = ctor;
break;
}
}

Debug.Assert(constructor != null);

var constructorMatcher = new ConstructorMatcher(constructor);
constructorMatcher.MapParameters(parameterMap, parameters);
return constructorMatcher.CreateInstance(provider);
}

#if NETCOREAPP
private static ConstructorInfoEx[] GetOrAddConstructors(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
// Not found. Do the slower work of checking for the value in the correct cache.
// Null and non-collectible load contexts use the default cache.
if (!type.Assembly.IsCollectible)
{
return s_constructorInfos.GetOrAdd(type, CreateConstructorInfoExs(type));
}

// Collectible load contexts should use the ConditionalWeakTable so they can be unloaded.
if (s_collectibleConstructorInfos.Value.TryGetValue(type, out ConstructorInfoEx[]? value))
{
return value;
}

value = CreateConstructorInfoExs(type);

// ConditionalWeakTable doesn't support GetOrAdd() so use AddOrUpdate(). This means threads
// can have different instances for the same type, but that is OK since they are equivalent.
s_collectibleConstructorInfos.Value.AddOrUpdate(type, value);
return value;
}
#endif // NETCOREAPP

private static ConstructorInfoEx[] CreateConstructorInfoExs(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
{
ConstructorInfo[] constructors = type.GetConstructors();
ConstructorInfoEx[]? value = new ConstructorInfoEx[constructors.Length];
for (int i = 0; i < constructors.Length; i++)
{
value[i] = new ConstructorInfoEx(constructors[i]);
}

return value;
}

/// <summary>
/// Create a delegate that will instantiate a type with constructor arguments provided directly
/// and/or from an <see cref="IServiceProvider"/>.
Expand DownExpand Up@@ -551,58 +637,82 @@ private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters,
return true;
}

private static object? GetService(IServiceProvider serviceProvider, ParameterInfo parameterInfo)
private sealed class ConstructorInfoEx
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public readonly ConstructorInfo Info;
public readonly ParameterInfo[] Parameters;
public readonly bool IsPreferred;
private readonly object?[]? _parameterKeys;

public ConstructorInfoEx(ConstructorInfo constructor)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
Info = constructor;
Parameters = constructor.GetParameters();
IsPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false);

for (int i = 0; i < Parameters.Length; i++)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
FromKeyedServicesAttribute? attr = (FromKeyedServicesAttribute?)
Attribute.GetCustomAttribute(Parameters[i], typeof(FromKeyedServicesAttribute), inherit: false);

if (attr is not null)
{
_parameterKeys ??= new object?[Parameters.Length];
_parameterKeys[i] = attr.Key;
}
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
// Try non keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}

private static bool IsService(IServiceProviderIsService serviceProviderIsService, ParameterInfo parameterInfo)
{
// Handle keyed service
if (TryGetServiceKey(parameterInfo, out object? key))
public bool IsService(IServiceProviderIsService serviceProviderIsService, int parameterIndex)
{
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
{
return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}
throw new InvalidOperationException(SR.KeyedServicesNotSupported);

// Use non-keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}
// Try non keyed service
return serviceProviderIsService.IsService(parameterInfo.ParameterType);
}

private static bool TryGetServiceKey(ParameterInfo parameterInfo, out object? key)
{
foreach (var attribute in parameterInfo.GetCustomAttributes<FromKeyedServicesAttribute>(false))
public object? GetService(IServiceProvider serviceProvider, int parameterIndex)
{
key = attribute.Key;
return true;
ParameterInfo parameterInfo = Parameters[parameterIndex];

// Handle keyed service
object? key = _parameterKeys?[parameterIndex];
if (key is not null)
{
if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
{
return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, key);
}

throw new InvalidOperationException(SR.KeyedServicesNotSupported);
}

// Use non-keyed service
return serviceProvider.GetService(parameterInfo.ParameterType);
}
key = null;
return false;
}

private readonly struct ConstructorMatcher
{
private readonly ConstructorInfo _constructor;
private readonly ParameterInfo[] _parameters;
private readonly ConstructorInfoEx _constructor;
private readonly object?[] _parameterValues;

public ConstructorMatcher(ConstructorInfo constructor)
public ConstructorMatcher(ConstructorInfoEx constructor)
{
_constructor = constructor;
_parameters = _constructor.GetParameters();
_parameterValues = new object?[_parameters.Length];
_parameterValues = new object[constructor.Parameters.Length];
}

public int Match(object[] givenParameters, IServiceProviderIsService serviceProviderIsService)
Expand All@@ -612,10 +722,10 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
Type? givenType = givenParameters[givenIndex]?.GetType();
bool givenMatched = false;

for (int applyIndex = 0; applyIndex < _parameters.Length; applyIndex++)
for (int applyIndex = 0; applyIndex < _constructor.Parameters.Length; applyIndex++)
{
if (_parameterValues[applyIndex] == null &&
_parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
_constructor.Parameters[applyIndex].ParameterType.IsAssignableFrom(givenType))
{
givenMatched = true;
_parameterValues[applyIndex] = givenParameters[givenIndex];
Expand All@@ -630,12 +740,12 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}

// confirms the rest of ctor arguments match either as a parameter with a default value or as a service registered
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (_parameterValues[i] == null &&
!IsService(serviceProviderIsService, _parameters[i]))
!_constructor.IsService(serviceProviderIsService, i))
{
if (ParameterDefaultValue.TryGetDefaultValue(_parameters[i], out object? defaultValue))
if (ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[i], out object? defaultValue))
{
_parameterValues[i] = defaultValue;
}
Expand All@@ -646,21 +756,21 @@ public int Match(object[] givenParameters, IServiceProviderIsService serviceProv
}
}

return _parameters.Length;
return _constructor.Parameters.Length;
}

public object CreateInstance(IServiceProvider provider)
{
for (int index = 0; index < _parameters.Length; index++)
for (int index = 0; index < _constructor.Parameters.Length; index++)
{
if (_parameterValues[index] == null)
{
object? value = GetService(provider, _parameters[index]);
object? value = _constructor.GetService(provider, index);
if (value == null)
{
if (!ParameterDefaultValue.TryGetDefaultValue(_parameters[index], out object? defaultValue))
if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[index], out object? defaultValue))
{
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _parameters[index].ParameterType, _constructor.DeclaringType));
throw new InvalidOperationException(SR.Format(SR.UnableToResolveService, _constructor.Parameters[index].ParameterType, _constructor.Info.DeclaringType));
}
else
{
Expand All@@ -677,7 +787,7 @@ public object CreateInstance(IServiceProvider provider)
#if NETFRAMEWORK || NETSTANDARD2_0
try
{
return _constructor.Invoke(_parameterValues);
return _constructor.Info.Invoke(_parameterValues);
}
catch (TargetInvocationException ex) when (ex.InnerException != null)
{
Expand All@@ -686,13 +796,13 @@ public object CreateInstance(IServiceProvider provider)
throw;
}
#else
return _constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
return _constructor.Info.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters: _parameterValues, culture: null);
#endif
}

public void MapParameters(int?[] parameterMap, object[] givenParameters)
{
for (int i = 0; i < _parameters.Length; i++)
for (int i = 0; i < _constructor.Parameters.Length; i++)
{
if (parameterMap[i] != null)
{
Expand DownExpand Up@@ -974,5 +1084,20 @@ private static object ReflectionFactoryCanonical(
return constructor.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, constructorArguments, culture: null);
}
#endif // NET8_0_OR_GREATER

#if NETCOREAPP
internal static class ActivatorUtilitiesUpdateHandler
{
public static void ClearCache(Type[]? _)
{
// Ignore the Type[] argument; just clear the caches.
s_constructorInfos.Clear();
if (s_collectibleConstructorInfos.IsValueCreated)
{
s_collectibleConstructorInfos.Value.Clear();
}
}
}
#endif
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Extensions.DependencyInjection;

namespace CollectibleAssembly
{
public class ClassToCreate
{
public object ClassAsCtorArgument { get; set; }

public ClassToCreate(ClassAsCtorArgument obj) { ClassAsCtorArgument = obj; }

public static object Create(ServiceProvider provider)
{
// Both the type to create (ClassToCreate) and the ctor's arg type (ClassAsCtorArgument) are
// located in this assembly, so both types need to be GC'd for this assembly to be collected.
return ActivatorUtilities.CreateInstance<ClassToCreate>(provider, new ClassAsCtorArgument());
}
}

public class ClassAsCtorArgument
{
}
}
Loading