Beispiel #1
0
        /// <summary>
        /// Given a generator and the instance map, generate an object.
        /// </summary>
        /// <returns>The created object.</returns>
        /// <param name="gen">The generator instance.</param>
        /// <param name="instances">A dictionary mapping provided types to a set of instances.</param>
        private object CreateInstance(IInstanceGenerator gen, IDictionary <Type, ConcurrentBag <object> > instances)
        {
            var args = new object[gen.Dependencies.Count()];
            var i    = 0;

            foreach (var dep in gen.Dependencies)
            {
                if (dep.IsConstructedGenericType && dep.GetGenericTypeDefinition() == typeof(IEnumerable <>))
                {
                    var depType = dep.GenericTypeArguments[0];

                    if (instances.TryGetValue(depType, out var set))
                    {
                        var arr = Array.CreateInstance(depType, set.Count);
                        Array.Copy(set.ToArray(), arr, set.Count);
                        args[i] = arr;
                    }
                    else
                    {
                        args[i] = Array.CreateInstance(depType, 0);
                    }
                }
                else
                {
                    if (instances[dep].Count <= 1)
                    {
                        args[i] = instances[dep].FirstOrDefault();
                    }
                    else
                    {
                        if (DuplicateResolver != null)
                        {
                            args[i] = DuplicateResolver(dep, instances[dep].ToArray());
                        }
                        else
                        {
                            throw new AmbiguousDependencyException(dep);
                        }
                    }
                }

                i++;
            }

            return(gen.GenerateInstance(args));
        }