Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reflection Constructor Binding Refactor #1155

Merged
merged 11 commits into from
Jun 29, 2020
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/Autofac/Autofac.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,10 @@
<AutoGen>True</AutoGen>
<DependentUpon>ProvidedInstanceActivatorResources.resx</DependentUpon>
</Compile>
<Compile Update="Core\Activators\Reflection\ConstructorParameterBindingResources.Designer.cs">
<Compile Update="Core\Activators\Reflection\BoundConstructorResources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>ConstructorParameterBindingResources.resx</DependentUpon>
<DependentUpon>BoundConstructorResources.resx</DependentUpon>
</Compile>
<Compile Update="Core\Activators\Reflection\MatchingSignatureConstructorSelectorResources.Designer.cs">
<DesignTime>True</DesignTime>
Expand Down Expand Up @@ -330,9 +330,9 @@
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>ProvidedInstanceActivatorResources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Update="Core\Activators\Reflection\ConstructorParameterBindingResources.resx">
<EmbeddedResource Update="Core\Activators\Reflection\BoundConstructorResources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>ConstructorParameterBindingResources.Designer.cs</LastGenOutput>
<LastGenOutput>BoundConstructorResources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Update="Core\Activators\Reflection\MatchingSignatureConstructorSelectorResources.resx">
<Generator>ResXFileCodeGenerator</Generator>
Expand Down
131 changes: 131 additions & 0 deletions src/Autofac/Core/Activators/Reflection/BoundConstructor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// This software is part of the Autofac IoC container
// Copyright © 2011 Autofac Contributors
// https://autofac.org
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;

namespace Autofac.Core.Activators.Reflection
{
/// <summary>
/// Represents the outcome of a single bind attempt by a <see cref="ConstructorBinder"/>.
/// </summary>
[SuppressMessage(
"Performance",
"CA1815:Override equals and operator equals on value types",
Justification = "Comparison of two BoundConstructor instances has no meaning.")]
public class BoundConstructor
{
private readonly Func<object?[], object>? _factory;
private readonly Func<object?>[]? _valueRetrievers;
private readonly ParameterInfo? _firstNonBindableParameter;

/// <summary>
/// Initializes a new instance of the <see cref="BoundConstructor"/> class for a successful bind.
/// </summary>
/// <param name="constructor">The constructor.</param>
/// <param name="factory">The instance factory.</param>
/// <param name="valueRetrievers">The set of value-retrieval functions.</param>
public BoundConstructor(ConstructorInfo constructor, Func<object?[], object> factory, Func<object?>[] valueRetrievers)
alistairjevans marked this conversation as resolved.
Show resolved Hide resolved
{
CanInstantiate = true;
TargetConstructor = constructor;
_factory = factory;
_valueRetrievers = valueRetrievers;
_firstNonBindableParameter = null;
}

/// <summary>
/// Initializes a new instance of the <see cref="BoundConstructor"/> class, for an unsuccessful bind.
/// </summary>
/// <param name="constructor">The constructor.</param>
/// <param name="firstNonBindableParameter">The first parameter that prevented binding.</param>
public BoundConstructor(ConstructorInfo constructor, ParameterInfo firstNonBindableParameter)
{
CanInstantiate = false;
TargetConstructor = constructor;
_firstNonBindableParameter = firstNonBindableParameter;
_factory = null;
_valueRetrievers = null;
}

/// <summary>
/// Gets the constructor on the target type. The actual constructor used
/// might differ, e.g. if using a dynamic proxy.
/// </summary>
public ConstructorInfo TargetConstructor { get; }

/// <summary>
/// Gets a value indicating whether the binding is valid.
/// </summary>
public bool CanInstantiate { get; }

/// <summary>
/// Invoke the constructor with the parameter bindings.
/// </summary>
/// <returns>The constructed instance.</returns>
public object Instantiate()
{
if (!CanInstantiate)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, BoundConstructorResources.CannotInstantitate, this.Description));
}

var values = new object?[_valueRetrievers!.Length];
for (var i = 0; i < _valueRetrievers.Length; ++i)
{
values[i] = _valueRetrievers[i]();
}

try
{
return _factory!(values);
}
catch (TargetInvocationException ex)
{
throw new DependencyResolutionException(string.Format(CultureInfo.CurrentCulture, BoundConstructorResources.ExceptionDuringInstantiation, TargetConstructor, TargetConstructor.DeclaringType.Name), ex.InnerException);
}
catch (Exception ex)
{
throw new DependencyResolutionException(string.Format(CultureInfo.CurrentCulture, BoundConstructorResources.ExceptionDuringInstantiation, TargetConstructor, TargetConstructor.DeclaringType.Name), ex);
}
}

/// <summary>
/// Gets a description of the constructor parameter binding.
/// </summary>
public string Description => CanInstantiate
? string.Format(CultureInfo.CurrentCulture, BoundConstructorResources.BoundConstructor, TargetConstructor)
: string.Format(CultureInfo.CurrentCulture, BoundConstructorResources.NonBindableConstructor, TargetConstructor, _firstNonBindableParameter);

/// <summary>Returns a System.String that represents the current System.Object.</summary>
/// <returns>A System.String that represents the current System.Object.</returns>
public override string ToString()
{
return Description;
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

188 changes: 188 additions & 0 deletions src/Autofac/Core/Activators/Reflection/ConstructorBinder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
// This software is part of the Autofac IoC container
// Copyright © 2011 Autofac Contributors
// https://autofac.org
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;

namespace Autofac.Core.Activators.Reflection
{
/// <summary>
/// Provides the functionality to bind a single constructor at resolve time.
/// </summary>
public class ConstructorBinder
{
private static readonly Func<ConstructorInfo, Func<object?[], object>> _factoryBuilder = GetConstructorInvoker;

private static ConcurrentDictionary<ConstructorInfo, Func<object?[], object>> _factoryCache = new ConcurrentDictionary<ConstructorInfo, Func<object?[], object>>();

private readonly ConstructorInfo _constructor;
private readonly ParameterInfo[] _constructorArgs;
private readonly Func<object?[], object>? _factory;
private readonly ParameterInfo? _illegalParameter;

/// <summary>
/// Initializes a new instance of the <see cref="ConstructorBinder"/> class.
/// </summary>
/// <param name="constructorInfo">The constructor.</param>
public ConstructorBinder(ConstructorInfo constructorInfo)
{
_constructor = constructorInfo ?? throw new ArgumentNullException(nameof(constructorInfo));
_constructorArgs = constructorInfo.GetParameters();

// If any of the parameters are unsafe, do not create an invoker, and store the parameter
// that broke the rule.
_illegalParameter = DetectIllegalParameter(_constructorArgs);

if (_illegalParameter is null)
{
// Build the invoker.
_factory = _factoryCache.GetOrAdd(constructorInfo, _factoryBuilder);
}
}

private static ParameterInfo? DetectIllegalParameter(ParameterInfo[] constructorArgs)
{
for (var idx = 0; idx < constructorArgs.Length; idx++)
{
if (constructorArgs[idx].ParameterType.IsPointer)
{
// Boo.
return constructorArgs[idx];
}
}

return null;
}

/// <summary>
/// Binds the set of parameters to the constructor. <see cref="BoundConstructor.CanInstantiate"/> indicates success.
/// </summary>
/// <param name="availableParameters">The set of all parameters.</param>
/// <param name="context">The current component context.</param>
/// <returns>The bind result.</returns>
public BoundConstructor Bind(IEnumerable<Parameter> availableParameters, IComponentContext context)
{
if (availableParameters is null)
{
throw new ArgumentNullException(nameof(availableParameters));
}

if (context is null)
{
throw new ArgumentNullException(nameof(context));
}

var constructorArgs = _constructorArgs;

if (_constructorArgs.Length == 0)
alistairjevans marked this conversation as resolved.
Show resolved Hide resolved
{
// No args, auto-bind with an empty value-retriever array to avoid the allocation.
return new BoundConstructor(_constructor, _factory!, Array.Empty<Func<object?>>());
}

if (_illegalParameter is object)
{
return new BoundConstructor(_constructor, _illegalParameter);
}

var valueRetrievers = new Func<object?>[constructorArgs.Length];

for (var idx = 0; idx < constructorArgs.Length; idx++)
{
var pi = constructorArgs[idx];
var foundValue = false;

foreach (var param in availableParameters)
{
if (param.CanSupplyValue(pi, context, out var valueRetriever))
{
valueRetrievers[idx] = valueRetriever;
foundValue = true;
break;
}
}

if (!foundValue)
{
return new BoundConstructor(_constructor, pi);
}
}

return new BoundConstructor(_constructor, _factory!, valueRetrievers);
}

private static Func<object?[], object> GetConstructorInvoker(ConstructorInfo constructorInfo)
{
var paramsInfo = constructorInfo.GetParameters();

var parametersExpression = Expression.Parameter(typeof(object[]), "args");
var argumentsExpression = new Expression[paramsInfo.Length];

for (int paramIndex = 0; paramIndex < paramsInfo.Length; paramIndex++)
{
var indexExpression = Expression.Constant(paramIndex);
var parameterType = paramsInfo[paramIndex].ParameterType;

var parameterIndexExpression = Expression.ArrayIndex(parametersExpression, indexExpression);

if (parameterType.IsPointer)
alistairjevans marked this conversation as resolved.
Show resolved Hide resolved
{
// We can't do anything with pointer arguments.
argumentsExpression[paramIndex] = Expression.Default(parameterType);
continue;
}

var convertExpression = parameterType.IsPrimitive
? Expression.Convert(ConvertPrimitiveType(parameterIndexExpression, parameterType), parameterType)
: Expression.Convert(parameterIndexExpression, parameterType);

if (!parameterType.IsValueType)
{
argumentsExpression[paramIndex] = convertExpression;
continue;
}

var nullConditionExpression = Expression.Equal(
parameterIndexExpression, Expression.Constant(null));
argumentsExpression[paramIndex] = Expression.Condition(
nullConditionExpression, Expression.Default(parameterType), convertExpression);
}

var newExpression = Expression.New(constructorInfo, argumentsExpression);
var lambdaExpression = Expression.Lambda<Func<object?[], object>>(newExpression, parametersExpression);

return lambdaExpression.Compile();
}

private static MethodCallExpression ConvertPrimitiveType(Expression valueExpression, Type conversionType)
{
var changeTypeMethod = typeof(Convert).GetRuntimeMethod(nameof(Convert.ChangeType), new[] { typeof(object), typeof(Type) });
return Expression.Call(changeTypeMethod, valueExpression, Expression.Constant(conversionType));
}
}
}