This repository has been archived by the owner on Nov 2, 2018. It is now read-only.
/
ConstructorCallSite.cs
56 lines (49 loc) · 1.97 KB
/
ConstructorCallSite.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.ExceptionServices;
namespace Microsoft.Extensions.DependencyInjection.ServiceLookup
{
internal class ConstructorCallSite : IServiceCallSite
{
private readonly ConstructorInfo _constructorInfo;
private readonly IServiceCallSite[] _parameterCallSites;
public ConstructorCallSite(ConstructorInfo constructorInfo, IServiceCallSite[] parameterCallSites)
{
_constructorInfo = constructorInfo;
_parameterCallSites = parameterCallSites;
}
public ConstructorInfo Constructor => _constructorInfo;
public object Invoke(ServiceProvider provider)
{
object[] parameterValues = new object[_parameterCallSites.Length];
for (var index = 0; index < parameterValues.Length; index++)
{
parameterValues[index] = _parameterCallSites[index].Invoke(provider);
}
try
{
return _constructorInfo.Invoke(parameterValues);
}
catch (Exception ex) when (ex.InnerException != null)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
// The above line will always throw, but the compiler requires we throw explicitly.
throw;
}
}
public Expression Build(Expression provider)
{
var parameters = _constructorInfo.GetParameters();
return Expression.New(
_constructorInfo,
_parameterCallSites.Select((callSite, index) =>
Expression.Convert(
callSite.Build(provider),
parameters[index].ParameterType)));
}
}
}