Symfony 3.4 在控制器操作中注入服务

Symfony 3.4 injection of service in controller action

services.yml

services:
  _defaults:
          autowire: true
          autoconfigure: true
          public: true 

控制器:

 /**
     * @Security("has_role('ROLE_USER')")
     * @Route("/", name="homepage")
     */
    public function indexAction(ContactService $contactService)
    {

错误

:indexAction()" requires that you provide a value for the "$contactService" argument.

我应该如何处理这个示例工作(自动向控制器方法注入服务)

在您的 services.yaml 文件中,您遗漏了两件事:

App\:
    resource: '../src/*'

App\Controller\:
    resource: '../src/Controller'
    tags: ['controller.service_arguments']

第一行告诉 Symfony 使 src/ 中的 classes 可用作服务。这将为每个 class 创建一个服务,其 id 是完全限定的 class 名称。

对于第二行,单独导入控制器以确保服务可以作为操作参数注入,即使您不扩展任何基本控制器class。

https://symfony.com/doc/current/service_container/3.3-di-changes.html

如果您没有使用新的 Symfony Flex 目录结构并且您仍在使用捆绑包,则配置略有不同:

AppBundle\:
    resource: '../../src/AppBundle/*'

AppBundle\Controller\:
    resource: '../../src/AppBundle/Controller'
    tags: ['controller.service_arguments']

https://symfony.com/doc/3.4/service_container/3.3-di-changes.html