11using System ;
22using System . Linq ;
33using System . Linq . Expressions ;
4+ using System . Reflection ;
45using Ploeh . AutoFixture ;
56
6- namespace TestStack . Dossier . BuildStrategies
7+ namespace TestStack . Dossier . Factories
78{
89 /// <summary>
910 /// Builds the object using the constructor with the most arguments.
1011 /// </summary>
11- public class UseConstructor : IBuildStrategy
12+ public class ConstructorFactory : IFactory
1213 {
1314 /// <inheritdoc />
1415 public TObject BuildObject < TObject , TBuilder > ( TestDataBuilder < TObject , TBuilder > builder )
@@ -24,24 +25,22 @@ public TObject BuildObject<TObject, TBuilder>(TestDataBuilder<TObject, TBuilder>
2425
2526 var parameterValues = longestConstructor
2627 . GetParameters ( )
27- . Select ( x => CallGetWithType ( x . Name , x . ParameterType , typeof ( TObject ) , typeof ( TBuilder ) ) ) ;
28+ . Select ( x => CallGetWithType ( x . Name , x . ParameterType , typeof ( TObject ) , typeof ( TBuilder ) , builder ) ) ;
2829
2930 return ( TObject ) longestConstructor . Invoke ( parameterValues . ToArray ( ) ) ;
3031 }
3132
32- private object CallGetWithType ( string propertyName , Type propertyType , Type objectType , Type builderType )
33+ private static object CallGetWithType ( string propertyName , Type propertyType , Type objectType , Type builderType , object builder )
3334 {
3435 // Make a Func<TObj, TPropertyType>
3536 var expressionDelegateType = typeof ( Func < , > ) . MakeGenericType ( objectType , propertyType ) ;
36-
37- // Make an expression parameter of type TObj
3837 var tObjParameterType = Expression . Parameter ( objectType ) ;
3938
40- var valueStoredInBuilder = builderType
39+ var closedGenericGetMethod = builderType
4140 . GetMethods ( )
42- . First ( method => method . Name == "Get" && method . ContainsGenericParameters && method . GetGenericArguments ( ) . Length == 1 )
43- . MakeGenericMethod ( propertyType )
44- . Invoke ( this , new object [ ]
41+ . First ( IsGenericGetMethod ( ) )
42+ . MakeGenericMethod ( propertyType ) ;
43+ var valueStoredInBuilder = closedGenericGetMethod . Invoke ( builder , new object [ ]
4544 {
4645 Expression . Lambda (
4746 expressionDelegateType ,
@@ -52,5 +51,9 @@ private object CallGetWithType(string propertyName, Type propertyType, Type obje
5251 return valueStoredInBuilder ;
5352 }
5453
54+ private static Func < MethodInfo , bool > IsGenericGetMethod ( )
55+ {
56+ return method => method . Name == "Get" && method . ContainsGenericParameters && method . GetGenericArguments ( ) . Length == 1 ;
57+ }
5558 }
5659}
0 commit comments