Skip to content

Instantly share code, notes, and snippets.

@markgibaud
Last active June 10, 2017 05:01
Show Gist options
  • Save markgibaud/4150878 to your computer and use it in GitHub Desktop.
Save markgibaud/4150878 to your computer and use it in GitHub Desktop.
NBuilder Utility
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using FizzWare.NBuilder;
namespace NBuilder
{
public static class NBuilderUtility
{
public static T Create<T>()
{
return (T)Create(typeof(T));
}
private static object Create(Type type)
{
if (type.IsInterface)
{
var firstConcreteImplementation = type.Assembly.GetTypes().FirstOrDefault(t => type.IsAssignableFrom(t) && !t.IsInterface);
if (firstConcreteImplementation != null)
type = firstConcreteImplementation;
else
return null;
}
var baseType = Build(type) ?? Build(Nullable.GetUnderlyingType(type));
var complexTypeProperties = baseType.GetType().GetProperties().Where(
p => !p.PropertyType.Namespace.Contains("System")).ToList();
if (!complexTypeProperties.Any())
return baseType;
foreach (var complexTypeProperty in complexTypeProperties)
complexTypeProperty.SetValue(baseType, Create(complexTypeProperty.PropertyType), null);
var genericListProperties = baseType.GetType().GetProperties()
.Where(p => p.PropertyType.Name == "List`1")
.ToList();
foreach (var propertyInfo in genericListProperties)
propertyInfo.SetValue(baseType,BuildGenericListOf(propertyInfo.PropertyType.GenericTypeArguments[0]));
return baseType;
}
private static object Build(Type type)
{
var builderClassType = typeof(Builder<>);
Type[] args = { type };
var genericBuilderType = builderClassType.MakeGenericType(args);
var builder = Activator.CreateInstance(genericBuilderType);
var createNewMethodInfo = builder.GetType().GetMethod("CreateNew");
var objectBuilder = createNewMethodInfo.Invoke(builder, null);
var buildMethodInfo = objectBuilder.GetType().GetMethod("Build");
return buildMethodInfo.Invoke(objectBuilder, null);
}
public static object BuildGenericListOf(Type type)
{
var listGeneric = typeof(List<>).MakeGenericType(type);
var list = Activator.CreateInstance(listGeneric);
var addMethodInfo = listGeneric.GetMethod("Add");
addMethodInfo.Invoke(list, new []{ Build(type)});
addMethodInfo.Invoke(list, new[] { Build(type) });
addMethodInfo.Invoke(list, new[] { Build(type) });
return list;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment