Reputation: 1143
I found this implementation of NBuilder here: https://gist.github.com/markgibaud/4150878
This works like a charm until I need to add some collection inside.
For example:
public class UserDto
{
public string UserName {get;set;}
public List<AddressDto> Addresses {get;set;} //this will be null
}
public class AddressDto
{
public string Street {get;set;}
//...
}
I want to fill any collection with at least one record.
I end up with this piece of code:
private static object BuildObjectList(Type type)
{
try
{
var builderClassType = typeof (Builder<>);
Type[] args = {type};
var genericBuilderType = builderClassType.MakeGenericType(args);
var builder = Activator.CreateInstance(genericBuilderType);
var createListOfSizeMethodInfo = builder.GetType().GetMethod("CreateListOfSize", new[] {typeof (int)});
var objectBuilder = createListOfSizeMethodInfo.Invoke(builder, new object[] {1});
var buildMethodInfo = objectBuilder.GetType().GetMethod("Build");
return buildMethodInfo.Invoke(objectBuilder, null);
}
catch (Exception ex)
{
Console.WriteLine(ex);
return null;
}
}
But there's some issue also when I try to invoke build method.
Upvotes: 1
Views: 555
Reputation: 2320
It looks like the Build
method you are trying to invoke requires parameters, but you're not passing it anything when you call buildMethodInfo.Invoke(objectBuilder, null);
The exception being thrown is TargetParameterCountException. From MSDN:
The exception that is thrown when the number of parameters for an invocation does not match the number expected.
You should step through the code using the debugger and inspect the prototype of the method that is being invoked to see what parameters it takes. Considering your comment that the same issue is seen when the Build
method is called in different ways (with no parameters passed to it), the implication is that the implementation of this method requires one or more parameters.
Alternatively, you could try calling the method statically, rather than through reflection, just to make sure that it can be called in the way the Invoke
is calling it.
Upvotes: 0