Skip to content

Commit

Permalink
Merge pull request #1155 from alistairjevans/constructor-binder
Browse files Browse the repository at this point in the history
Reflection Constructor Binding Refactor
  • Loading branch information
tillig committed Jun 29, 2020
2 parents 999154e + 16e5b89 commit f7275cd
Show file tree
Hide file tree
Showing 20 changed files with 607 additions and 284 deletions.
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
159 changes: 159 additions & 0 deletions src/Autofac/Core/Activators/Reflection/BoundConstructor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
// 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="binder">The binder that generated this binding.</param>
/// <param name="factory">The instance factory.</param>
/// <param name="valueRetrievers">The set of value-retrieval functions.</param>
[SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "Validated in constructor.")]
public static BoundConstructor ForBindSuccess(ConstructorBinder binder, Func<object?[], object> factory, Func<object?>[] valueRetrievers)
=> new BoundConstructor(binder, factory, valueRetrievers);

/// <summary>
/// Initializes a new instance of the <see cref="BoundConstructor"/> class, for an unsuccessful bind.
/// </summary>
/// <param name="binder">The binder that generated this binding.</param>
/// <param name="firstNonBindableParameter">The first parameter that prevented binding.</param>
public static BoundConstructor ForBindFailure(ConstructorBinder binder, ParameterInfo firstNonBindableParameter) =>
new BoundConstructor(binder, firstNonBindableParameter);

/// <summary>
/// Initializes a new instance of the <see cref="BoundConstructor"/> class for a successful bind.
/// </summary>
/// <param name="binder">The binder that generated this binding.</param>
/// <param name="factory">The instance factory.</param>
/// <param name="valueRetrievers">The set of value-retrieval functions.</param>
internal BoundConstructor(ConstructorBinder binder, Func<object?[], object> factory, Func<object?>[] valueRetrievers)
{
CanInstantiate = true;
Binder = binder;
_factory = factory ?? throw new ArgumentNullException(nameof(factory));
_valueRetrievers = valueRetrievers ?? throw new ArgumentNullException(nameof(valueRetrievers));
_firstNonBindableParameter = null;
}

/// <summary>
/// Initializes a new instance of the <see cref="BoundConstructor"/> class, for an unsuccessful bind.
/// </summary>
/// <param name="binder">The binder that generated this binding.</param>
/// <param name="firstNonBindableParameter">The first parameter that prevented binding.</param>
internal BoundConstructor(ConstructorBinder binder, ParameterInfo firstNonBindableParameter)
{
Binder = binder;
CanInstantiate = false;
_firstNonBindableParameter = firstNonBindableParameter ?? throw new ArgumentNullException(nameof(firstNonBindableParameter));
_factory = null;
_valueRetrievers = null;
}

/// <summary>
/// Gets the binder that created this binding.
/// </summary>
public ConstructorBinder Binder { get; }

/// <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 => Binder.Constructor;

/// <summary>
/// Gets the total number of arguments for the bound constructor.
/// </summary>
public int ArgumentCount => Binder.ParameterCount;

/// <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.

0 comments on commit f7275cd

Please sign in to comment.