问题
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