public static IInstanceCreator ForInstanceCreator(Type targetType, IInstanceCreator creator) { Debug.Assert(creator != null); Debug.Assert(targetType != null); Debug.Assert(targetType.IsGenericType && targetType.GetGenericTypeDefinition( ) == typeof(IInstanceCreator <>)); IInstanceCreator finalCreator = creator; Type creatorType = creator.GetType( ); Type targetCreatedType = targetType.GetGenericArguments( )[0]; // Ensure target type is closed. Type finalTargetType = targetType; if (finalTargetType.ContainsGenericParameters) { targetCreatedType = GenericTypeResolver.GetCorrespondingBaseTypes(finalCreator.InstanceType, targetCreatedType).Single( ); finalTargetType = typeof(IInstanceCreator <>).MakeGenericType(targetCreatedType); } // If the creator does not have the same type as the target, wrap the creator to return instances of the target base type. if (!creatorType.Is(finalTargetType)) { Type actualCreatedType = creatorType.GetInterfaces( ) .Single(i => i.IsGenericType && i.GetGenericTypeDefinition( ) == typeof(IInstanceCreator <>)) .GetGenericArguments( )[0]; Type wrapperType = typeof(InstanceCreatorWrapper <,>).MakeGenericType(targetCreatedType, actualCreatedType); finalCreator = (IInstanceCreator)Activator.CreateInstance(wrapperType, creator); } // Get IInstanceCreator to return the given creator instance. Type funcType = typeof(Func <>).MakeGenericType(finalTargetType); var lambda = Expression.Lambda(funcType, Expression.Constant(finalCreator, finalTargetType)); var nestingCreator = WeakInstanceCreator.ForDelegate(lambda.Compile( )); return(nestingCreator); }