3

services.yml

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

Controller:

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

Error

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

What i should do to this example work (auto inject service to controller method)

Nek
  • 2,715
  • 1
  • 20
  • 34
Developer
  • 2,731
  • 2
  • 41
  • 71

1 Answers1

9

In your services.yaml file, you're missing 2 things:

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

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

The first line tells Symfony to make classes in src/ available to be used as services. This creates a service per class whose id is the fully-qualified class name.

For the second line, controllers are imported separately to make sure services can be injected as action arguments even if you don't extend any base controller class.

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

If you're not using the new Symfony Flex directory structure and you're still using bundles, the config is a little different:

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

fxbt
  • 2,556
  • 19
  • 19
  • Can you give the source documentation for services from action methods? :) – Nek Apr 12 '18 at 10:12
  • What is example for vendor bundles - resource: '../../vendor/easycorp/easyadmin-bundle/src/Controller' - dont work – Developer Apr 12 '18 at 10:55
  • Your example dont work - for my, this work resource: '../../src/AppBundle/Controller' this dont work resource: '../src/AppBundle/Controller' and for vendor - i cannot find way to work example : resource: 'vendor/easycorp/easyadmin-bundle/src/Controller' – Developer Apr 12 '18 at 10:59
  • @GregHmhmm Did you adapted the namespace as well ? `AppBundle\Controller\: resource: '../src/AppBundle/Controller'` – fxbt Apr 12 '18 at 11:03