Laravel IOC not calling the constructor

坚强是说给别人听的谎言 提交于 2020-03-05 04:59:47

问题


I have binding in the service provider

$this->app->singleton(
    'App\Models\Subscription\Interfaces\IInvoiceService',
    'App\Models\Subscription\Impl\InvoiceService'
);



class InvoiceService implements  IInvoiceService
{

    protected $repo;


    public function _construct(){

        $this->app = App::getFacadeRoot();

        $this->repo = $this->app['repo'];


    }
    public function Create()
    {
    }
 }

In one of the classes in Injected the IInovoice Service.

I am getting the concrete implementation of IInovoice . but the Constructor of the InvoiceService is never getting called


回答1:


Try the following

class InvoiceService implements  IInvoiceService
{

    protected $app;
    protected $repo;

    public function _construct($app, $repo) {

        $this->app = $app;
        $this->repo = $repo;
    }

    public function Create() {

    }

 }

App\Providers\AppServiceProvider

public function register() {

      $this->app->singleton(
          'App\Models\Subscription\Interfaces\IInvoiceService',
          'App\Models\Subscription\Impl\InvoiceService'
      );


      $this->app->when('App\Models\Subscription\Impl\InvoiceService')
        ->needs('$app')
        ->give($this->app->getFacadeRoot());

      $this->app->when('App\Models\Subscription\Impl\InvoiceService')
        ->needs('$repo')
        ->give($this->app['repo']);
}

public function boot(ResponseFactory $response) {

      //uncomment this line to debug InvoiceService Resolving event

      //$this->app->resolving(App\Models\Subscription\Impl\InvoiceService::class, function ($invoiceService, $app)    {
        //dump('resolves InvoiceService', $invoiceService);
      //});
}

Then run

php artisan clear-compiled
php artisan config:clear


来源:https://stackoverflow.com/questions/60207552/laravel-ioc-not-calling-the-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!