Home » Php » php – Symfony 3.4 : Cannot autowire service : argument of method "__construct()" has no type-hint, you should configure its value explicitly

php – Symfony 3.4 : Cannot autowire service : argument of method "__construct()" has no type-hint, you should configure its value explicitly

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying to define service using Symfony 3.4 DI but I got the following error :

Cannot autowire service “AppBundle\Service\SelectionWeb”: argument “$config” of method “__construct()” has no type-hint, you should configure its value explicitly.

..But I did configure its value.

Here are my conf files:

AppBundle\Service\Myservice

<?php
public function __construct(Security $security, SessionInterface $session, EntityManagerInterface $em, $config)
{
}

AppBundle\Ressources\config\services.yml

myservice:
    public: true
    class: AppBundle\Service\Myservice
    arguments:
        $config: 'test'

I also tried:

myservice:
    public: true
    class: AppBundle\Service\Myservice
    arguments:
        $config: '%config%' # %config% defined in AppBundle/Ressource/config/parameter.yml as array

and

myservice:
    public: true
    class: AppBundle\Service\Myservice
    bind:
        $config: "@=parameter('config')"

Thanks to @Cerad it works now using this:

AppBundle\Service\Myservice:
    # public mean if service can be get from container
    # if false consider using DI
    public: true
    autowire: true
    arguments:
        $config: '%config%'

The remaining question is why it doesn’t affect all services ? I have more than one service where I inject $config as argument using bind and there is no issues

AppBundle\Service\SearchEngine

public function __construct(RequestStack $requestStack, EntityManagerInterface $em, TranslatorInterface $translator, Tools $tools, array $config)

AppBundle\ressources\config\services.yml

services:
    searchEngine: # no problem here when inject $config manually
        public: true
        class: AppBundle\Service\SearchEngine
        autowire: true
        bind:
            $config: "@=parameter('config')"

    #before not working
    myservice:
        public: true
        class: AppBundle\Service\Myservice
        autowire: true
        arguments:
            $config: '%config%'

    #After working
    AppBundle\Service\Myservice:
        public: true
        autowire: true
        arguments:
            $config: '%config%'
How to&Answers: