Veleous
102
0
Laravel

BindingResolutionException when resolving a ServiceProvider

Posted 1 year ago by Veleous

I'm attempting to create a service provider which will inject a dependency into a controller, however, I encounter a BindingResolutionException when attempting to access the controller.

The exact exception message I receive is:

(1/1) BindingResolutionException Target [Stockholm\Address\Domain\Handler\HandlerInterface] is not instantiable while building [App\Http\Controllers\CityController].

I define my ServiceProvider as such.

    <?php

    // app/Providers/AddressServiceProvider.php

    namespace App\Providers;

    use App\Http\Controllers\CityController;
    use Illuminate\Support\ServiceProvider;
    use Stockholm\Address\Domain\Handler\CityHandler;
    use Stockholm\Address\Domain\Handler\HandlerInterface;

    class AddressServiceProvider extends ServiceProvider
    {
        protected $defer = true;

        public function register()
        {
            $this->app->when(CityController::class)
                ->needs(HandlerInterface::class)
                ->give(function() {
                    return new CityHandler();
                });
        }

        public function provides()
        {
            return [
                CityHandler::class
            ];
        }
    }

Register the ServiceProvider in the Providers array.

    <?php
    
    // config/app.php
    
    return [
      'providers' => [
        // clipped
        App\Providers\AddressServiceProvider::class,
      ]
    ]

Define my HandlerInterface.

    <?php
    
    // stockholm/Address/Domain/Handler/HandlerInterface.php
    
    namespace Stockholm\Address\Domain\Handler;
    
    interface HandlerInterface
    {
        // clipped
    }

Define my implementation of the HandlerInterface.

    <?php
    
    // stockholm\Address\Domain\Handler\CityHandler.php
    
    namespace Stockholm\Address\Domain\Handler;
    
    class CityHandler implements HandlerInterface
    {
        // clipped
    }

Add the HandlerInterface as a Constructor argument to my CityController.

   <?php
    
    // app/Http/Controllers/CityController.php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use Stockholm\Address\Domain\Handler\HandlerInterface;
    
    class CityController extends Controller
    {
        private $handler;

        public function __construct(HandlerInterface $handler)
        {
            $this->handler = $handler;
        }
    }

My PSR-4 autoload configuration in my composer.json file looks as below.

    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\": "app/",
            "Stockholm\": "stockholm/"
        }
    },

Please sign in or create an account to participate in this conversation.