2017-12-11 2 views
0

종속성 주입을 사용하여 클래스를 생성하려고합니다. 이 클래스는이 서비스 제공IOC contatiner laravel을 사용하여 클래스를 인스턴스화 할 수 없습니다.

class SomethingServiceProvider extends ServiceProvider 
{ 

    public function boot() 
    { 

    } 


    public function register() 
    { 
     $this->app->singleton('Something', function() { 
      return new Something('test'); 
     }); 
    } 
} 

내가 컨트롤러에서이 클래스의 인스턴스를 사용하려고 할 때 ... app.php

class Something 
{ 
     private $variable; 

     public function __construct(string $variable) 
     { 
      $this->variable = $variable; 
     } 
} 

에 등록 된 자신의 서비스 제공을 가지고

class TestController extends AppBaseController 
{ 
    public function __construct(Something $something) 
    { 
     $this->something = $something; 
    } 
... 

오류가 발생했습니다.

"Unresolvable dependency resolving [Parameter #0 [ string $variable ]] in class Something at Container->unresolvablePrimitive(object(ReflectionParameter)) in Container.php (line 848) "

답변

0

YourServiceProvider::__construct은 유형이 지정되지 않은 $app 인스턴스를 허용한다고 생각합니다. 이는 Laravel이 자동으로 해결할 수 없음을 의미합니다. 타이핑 해보십시오. public function __construct(Application $app)에 적절한 use 문을 지정하십시오.

더 :

+0

내가 여기에 실종 된지 확실하지 않습니다. 서비스 공급자에는 생성자가 없습니다. – apokryfos

0

당신이 뭔가를 등록 https://laravel.com/docs/5.3/container#automatic-injection는 정규화 된 클래스 이름을 사용할 필요가 주입되는 :

public function register() 
{ 
    $this->app->singleton(Something::class, function() { 
     return new Something('test'); 
    }); 
} 

그렇지 않으면 Laravel은 자동으로 시도됩니다 것을 의미한다 뭔가를 주입하려고합니다 먼저 Something의 종속성을 주입 한 다음 이것이 문자열이고 실패한 것으로 판별하십시오.

관련 문제