douzun4443
douzun4443
2017-12-11 07:51

无法使用IOC contatiner laravel实例化类

已采纳

I`m trying to get instanse of my class using dependency injection. This class has own service provider that registered in app.php

 class Something
 {
      private $variable;

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

this is service provider

class SomethingServiceProvider extends ServiceProvider
{

    public function boot()
    {

    }


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

and when I try to use this class instance in controller...

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

I got error:

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongzhao4036 dongzhao4036 4年前

    I guess YourServiceProvider::__construct accepts a non-typed $app instance. This means that Laravel cannot automatically resolve it. Try typing it; public function __construct(Application $app) with the proper use-statement.

    More: https://laravel.com/docs/5.3/container#automatic-injection

    点赞 评论 复制链接分享
  • doujia9204 doujia9204 4年前

    When you register something to be injected you need to use the fully qualified class name:

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

    Otherwise Laravel will try to automatically inject something which implies that it will try to inject the dependencies of Something first and then determine that this is a string and fail.

    点赞 评论 复制链接分享