Laravel __construct() - 没有注入?

I am getting error:

GitHubApp::__construct() must be an instance of App\Project\Repositories\GitProviderRepository

I thought Laravel does some kind of magic when it come to __construct() so i don't have to inject it into new GitHubApp();?

  use App\Project\Repositories\GitProviderRepository;

    class GitHubApp
    {
        private $gitProviderRepository;

        public function __construct(GitProviderRepository $gitProviderRepository)
        {
            $this->gitProviderRepository = $gitProviderRepository;
        }
    }

In other class:

return new GitHubApp();

When calling new GithubApp(), you relied on yourself to build the GithubApp instance, Laravel does not responsible for building that instance.

You have to let Laravel resolve the dependencies for you. There are numbers of way to achieve this:

Using App facade:

App::make(GithubApp::class);

Using app() helper method:

app(GithubApp::class);

Or using the resolve() helper method:

resolve(GithubApp::class);

Behind the scene, your class type and its dependencies will be resolved and instantiated by the Illuminate\Container\Container class (the parent class of Application). Specifically by the make() and build() methods.

Hope this help! :)

You can try as:

return app(GitHubApp::class);

or

return app()->make(GitHubApp::class)

It is done by the powerful IoC container of Laravel to resolve classes without any configuration.

When a type is not bound in the container, it will use PHP's Reflection facilities to inspect the class and read the constructor's type-hints. Using this information, the container can automatically build an instance of the class.

Docs