20

I'm starting to working with Symfony4 and I meet the following error when I try to run my server: Cannot autowire service "App\Controller\CharacterInformation": argument "$region" of method "__construct()" is type-hinted "string", you should configure its value explicitly.

How I instantiate my class:

 /**
 * @Route("/")
 * @return Response
 */
function mainPage() {
    $characterInformation = new CharacterInformation('eu');
    return new Response($characterInformation->getCharacter());
}

The constructor of CharacterInformation:

 /**
 * @var int
 */
public function __construct(string $region) {
        $this->apiInformation = new ApiContent($region);
}

The constructor of ApiContent:

    public function __construct(string $region) {
    $apiToken = new ApiToken($region);
    $this->token = $apiToken->getToken();
    $this->region = $apiToken->getRegion();
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322

2 Answers2

16

Try to set autowire information into config/services.yaml. Like:

#app.myservice.config:
    App\Controller\CharacterInformation:
        arguments:
            $region: "%region%"

Check all information into Defining Services Dependencies Automatically (Autowiring)

Dmytro
  • 321
  • 1
  • 10
  • 3
    I did exactly that and nothing changed. I even tried to put that in _defaults.bind section – afilina Mar 19 '19 at 01:04
  • Hey @afilina , are you saw Karringan answer below? – Dmytro Mar 19 '19 at 14:40
  • 3
    Yes. That didn't help. In the end, I found out that my yaml file that was defining the service wasn't being loaded, therefore the string args didn't kick in. – afilina Mar 19 '19 at 18:12
4

Also you can resolve this problem by binding parameters in your services.yml file.

Here is well explained https://stackoverflow.com/a/49084402

    # config.yml
    parameters:
      foo: 'secret'

    services:
      _defaults:
         autowire: true
         bind:
           $fooKey: '%foo%'
Smarquina
  • 113
  • 6