public object CreateInstance(IServiceProvider provider) { for (int i = 0; i != this._parameters.Length; i++) { if (!this._parameterValuesSet[i]) { object service = provider.GetService(this._parameters[i].ParameterType); if (service == null) { object obj = default(object); if (!ParameterDefaultValue.TryGetDefaultValue(this._parameters[i], out obj)) { throw new InvalidOperationException(string.Format("Unable to resolve service for type '{0}' while attempting to activate '{1}'.", this._parameters[i].ParameterType, this._constructor.DeclaringType)); } this._parameterValues[i] = obj; } else { this._parameterValues[i] = service; } } } try { return(this._constructor.Invoke(this._parameterValues)); } catch (TargetInvocationException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw; } }
private static Expression BuildFactoryExpression(ConstructorInfo constructor, int?[] parameterMap, Expression serviceProvider, Expression factoryArgumentArray) { ParameterInfo[] parameters = constructor.GetParameters(); Expression[] array = new Expression[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { ParameterInfo obj = parameters[i]; Type parameterType = obj.ParameterType; object value = default(object); bool flag = ParameterDefaultValue.TryGetDefaultValue(obj, out value); if (parameterMap[i].HasValue) { array[i] = Expression.ArrayAccess(factoryArgumentArray, Expression.Constant(parameterMap[i])); } else { Expression[] arguments = new Expression[4] { serviceProvider, Expression.Constant(parameterType, typeof(Type)), Expression.Constant(constructor.DeclaringType, typeof(Type)), Expression.Constant(flag) }; array[i] = Expression.Call(ActivatorUtilities.GetServiceInfo, arguments); } if (flag) { ConstantExpression right = Expression.Constant(value); array[i] = Expression.Coalesce(array[i], right); } array[i] = Expression.Convert(array[i], parameterType); } return(Expression.New(constructor, array)); }