symfony v3.4 unable to guess autowiring
使用自动装配功能时,Symfony v3.4无法猜测参数。
Cannot autowire service"AppBundle\\Service\\MyServiceConfig": argument"$key" of method"__construct()" has no type-hint, you should configure its value explicitly.
我还明确定义了该参数,但是它仍然不起作用,该参数的类型为
1 2 3 4 5 6 7 8 9 10 | services: app.myservice.config: class: AppBundle\\Service\\MyServiceConfig public: true arguments: ["%app_key%"] #defined in parameter.yml app.myservice class: AppBundle\\Service\\MyService public: true arguments: ["@app.myservice.config"] |
哪个工作正常,当我调用服务时可以看到预期的结果。
但是,当我编写AppExtension时,出现了以上错误:
1 2 3 4 5 | app.twig.my_app_extension: class: AppBundle\\Twig\\MyAppExtension arguments: ["@app.myservice" ] tags: - { name: twig.extension } |
所以我明确定义了参数
1 2 3 4 5 | app.myservice.config: class: AppBundle\\Service\\MyServiceConfig public: true arguments: $key: "%app_key%" #defined in parameter.yml |
它仍然不起作用
这是MyServiceConfig类的外观:
1 2 3 4 5 6 7 8 9 10 11 | class MyServiceConfig implements MyServiceConfigInterface { /** * @var string */ private $key; public function __construct($key){ $this->key= $key; } } |
MyAppExtension类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /** * The MyAppExtension class */ class MyAppExtension extends \\Twig_Extension { /** * @var MyServiceConfigInterface $key */ private $key; public function __construct(MyServiceConfigInterface $key){ $this->key= $key; } } |
此处提供的解决方案也无济于事,因为我在
中包含了service.yml
所以我很无聊。将您的app / config / services.yml文件更新为:
1 2 3 4 5 6 7 8 9 10 | #app.myservice.config: AppBundle\\Service\\MyServiceConfig: # public: true arguments: $key:"%key%" #app.myservice: # class: AppBundle\\Service\\MyAppService # arguments: ["@app.myservice.config"] # public: true |
您的TwigExtension类型针对MyAppServiceInterface提示。因此,autowire在容器中查找ID为MyAppServiceInterface的服务。它根本不查看class参数。现在,在您的情况下,您可以使用MyAppService来实现您的界面,并且自动装配足够聪明,可以识别出您的界面只有一种实现。
要健壮一些,以便将实现显式地别名到接口上,以防止在您决定添加另一个实现时出现问题。在这种情况下不是绝对必要。
1 2 3 4 | AppBundle\\Service\\MyServiceConfig: { $key:"%key%" } # Just showing off here AppBundle\\Service\\MyServiceConfigInterface: '@AppBundle\\Service\\MyServiceConfig' |
还有另一件无关的事情:不要调用您的树枝扩展类AppBundleExtension。似乎您正在将树枝扩展与捆绑扩展混合在一起。两种不同的概念。并不重要,但可能会使您感到困惑。