第三方捆绑包的依赖项注入失败

时间:2019-04-16 09:36:57

标签: dependency-injection symfony4

当我运行以下代码(标准依赖项注入)时:

use Khill\Lavacharts\Lavacharts;

class MainController extends AbstractController {

  protected $lavacharts;

  function __construct(Lavacharts $lavacharts) {
    $this->lavacharts = $lavacharts;
  }

我得到了错误:

Cannot autowire service "DefaultController": 
argument "$lavacharts" of method "MainController::__construct()" 
references class "Khill\Lavacharts\Lavacharts" but no such 
service exists. You should maybe alias this class to the 
existing "lavacharts" service

因此,我在services.yml的lavachart服务中添加了一个别名,它是一个供应商捆绑包,如下所示:

Khill\Lavacharts\Lavacharts\: "@lavacharts"

这是供应商定义lavacharts服务的方式:

parameters:
    khill.lavacharts.class: Khill\Lavacharts\Lavacharts
    khill.lavacharts.twig: Khill\Lavacharts\Symfony\Bundle\Twig\LavachartsExtension

services:
    lavacharts:
        class: "%khill.lavacharts.class%"

    lavacharts.twig_extension:
        class: "%khill.lavacharts.twig%"
        public: false
        arguments: ['@lavacharts']
        tags:
            - { name: twig.extension }

但这无法正常工作,尽管我感觉自己创建了预期的别名(基于the official documentation),但我仍然遇到相同的错误。我想念什么?

1 个答案:

答案 0 :(得分:0)

啊!好的,我自己找到了。

在服务声明中,应省略尾部反斜杠(我还不明白为什么要这样):

Khill\Lavacharts\Lavacharts: "@lavacharts"

而不是

Khill\Lavacharts\Lavacharts\: "@lavacharts"

(请注意尾随反斜杠的区别)