Exemple #1
0
 TTarget IAutoConfiguration.Make <TTarget>()
 {
     if (typeof(TTarget) == typeof(T))
     {
         throw new InvalidOperationException("Preventing operation that would cause infinite recursion.");
     }
     return((TTarget)builder.CreateObject(typeof(TTarget)));
 }
Exemple #2
0
        private object CreateNewObject(Type type)
        {
            if (type.IsInterface || type.IsAbstract)
            {
                return(interfaceBuilder.CreateObject(type));
            }

            // if recursing within constructor, attempt to return
            // unconstructed instance or null
            var key = type.CreateKey();

            if (constructCache.Contains(key))
            {
                return(ConstructorlessType(type));
            }

            // prevent constructor recursion, further attempts to generate this type
            // within it's constructor return null
            constructCache.Add(key);

            // try public constructors
            var arr = type.GetConstructors().Where(c => ConstructorDoesNotContainType(c, type)).Select(p => p).ToArray();

            if (arr.Length != 0)
            {
                // try construct using least parameters
                var info = arr.OrderBy(o => GetConstructorParamsWeighting(o.GetParameters())).ElementAtOrDefault(0);
                if (info != null)
                {
                    var pArr = info.GetParameters();
                    var args = pArr.Select(p => CreateObject(p.ParameterType)).ToArray();
                    return(info.Invoke(args));
                }
            }

            // try non-public constructors
            arr = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).Where(
                c => ConstructorDoesNotContainType(c, type)).Select(p => p).ToArray();
            if (arr.Length != 0)
            {
                // try construct using least parameters
                var info = arr.OrderBy(o => GetConstructorParamsWeighting(o.GetParameters())).ElementAtOrDefault(0);
                if (info != null)
                {
                    var pArr = info.GetParameters();
                    var args = pArr.Select(p => CreateObject(p.ParameterType)).ToArray();
                    return(info.Invoke(args));
                }
            }

            // initialize without constructor
            return(ConstructorlessType(type));
        }
Exemple #3
0
        private void FillDictionary(object o)
        {
            if (config.GetEnumerableSize() > 0)
            {
                var        type      = o.GetType();
                MethodInfo addMethod = type.GetMethod("Add");
                var        args      = type.GetGenericArguments();

                var key   = builder.CreateObject(args[0]);
                var value = builder.CreateObject(args[1]);
                addMethod.Invoke(o, new[] { key, value });
            }
        }