private function createSharedInstance($nid, array $rule, array $args) {
        if (!empty($rule['factory'])) {
            // The instance is created with a user-supplied factory function.
            $callback = $rule['factory'];
            $function = $this->reflectCallback($callback);

            if ($function->getNumberOfParameters() > 0) {
                $callbackArgs = $this->resolveArgs(
                    $this->makeDefaultArgs($function, (array)$rule['constructorArgs']),
                    $args
                );

                $this->instances[$nid] = null; // prevent cyclic dependency from infinite loop.
                $this->instances[$nid] = $instance = call_user_func_array($callback, $callbackArgs);
            } else {
                $this->instances[$nid] = $instance = $callback();
            }

            // Reflect on the instance so that calls can be made against it.
            if (is_object($instance)) {
                $class = new \ReflectionClass(get_class($instance));
            }
        } else {
            $className = empty($rule['class']) ? $nid : $rule['class'];
            if (!class_exists($className)) {
                throw new NotFoundException("Class $className does not exist.", 404);
            }
            $class = new \ReflectionClass($className);
            $constructor = $class->getConstructor();

            if ($constructor && $constructor->getNumberOfParameters() > 0) {
                // Instantiate the object first so that this instance can be used for cyclic dependencies.
                $this->instances[$nid] = $instance = $class->newInstanceWithoutConstructor();

                $constructorArgs = $this->resolveArgs(
                    $this->makeDefaultArgs($constructor, (array)$rule['constructorArgs'], $rule),
                    $args
                );
                $constructor->invokeArgs($instance, $constructorArgs);
            } else {
                $this->instances[$nid] = $instance = new $class->name;
            }
        }

        // Call subsequent calls on the new object.
        if (isset($class) && !empty($rule['calls'])) {
            foreach ($rule['calls'] as $call) {
                list($methodName, $args) = $call;
                $method = $class->getMethod($methodName);

                $args = $this->resolveArgs(
                    $this->makeDefaultArgs($method, $args, $rule),
                    [],
                    $instance
                );

                $method->invokeArgs($instance, $args);
            }
        }

        return $instance;
    }