lucidarch/laravel

How to inject dependencies from the IoC Container

CROSP opened this issue · 4 comments

CROSP commented

Hi,

I have the following problem. I've defined a repository interface and an implementation as follows:

interface UserRepositoryContract extends BaseRepository {
	function getAllUsers();
}

And in the service provider, I register this repository as a singleton:

class DataRepositoriesProvider extends ServiceProvider {
	/**
	 * Register services.
	 *
	 * @return void
	 */
	public function register() {
		$this->app->singleton( UserRepositoryContract::class, UsersRepository::class );
	}

}

But how to inject these dependencies into a Feature or a Job. When I try to inject via a constructor, I get the following error:

Unable to map parameter [userRepository] to command [App\Services\Web\Features\Admin\HomePageDashboardFeature]

But these dependencies are successfully injected into controllers and controllers' actions.
What is the right way to inject dependencies?
I have found only one solution to create a Feature manually passing all required dependencies like that:

public function homePage( UserRepositoryContract $usersRepository ) {
	return $this->serve( HomePageDashboardFeature::class, [ 'usersRepository' => $usersRepository ] );
}

Is it fine to do in that way?

I would be grateful for any comments and suggestions!

Hey @CROSP, I suggest that you inject your dependencies inside inside handle() method of Jobs.
Use Jobs to document the "steps" of your Feature.

Example:
Create a Job (e.g. GetUsersJob) and add your repository's dependency in that job. Now you'll have a Job that will fetch all your users and can be re-used across multiple Features in your app.

class FetchUsersJob extends Job
{
    public function handle(UserRepositoryContract $usersRepository)
    {
        return $usersRepository->getAllUsers();
    }
}
CROSP commented

@harris21 , omg, I am really confused :) This was the first way I tried to use to inject dependencies. This looks pretty nice from the architectural perspective. I tried to do that yesterday and got the same error as described above, however I've just tried again and it works perfectly, lol :)
I appreciate your help!

I am glad that it worked, cheers!