Symfony 4构造函数参数Autowire报错求助(Symfony2.8正常)
Hey there, let's work through this dependency injection issue you're hitting in Symfony 4—especially since your setup worked perfectly in 2.8.
What's Causing the Error?
Symfony 4+ relies heavily on autowiring by default, which works seamlessly for class/interface type hints (the container can match these to existing services automatically). But arrays don't have a unique, recognizable type that autowiring can use to resolve values.
In Symfony 2.8, you likely had explicit service configuration that handled the array parameter, or autowiring wasn't enabled by default—so the container knew exactly where to pull the array value from. Your string parameters are working because either they're tied to named parameters Symfony can resolve via binding, or you have explicit config for those arguments elsewhere.
How to Fix It
You have two simple, reliable solutions to get your array parameter injected correctly:
1. Explicitly Map the Argument in Your Service Config
In your service.yaml, add an explicit argument mapping for App\Class, linking the $securityConfiguration constructor parameter to your array parameter:
services: # ... other existing services ... App\Class: arguments: $securityConfiguration: '%security.configuration%'
Just replace %security.configuration% with the actual name of your array parameter from the parameters section of your config.
2. Use Global Parameter Binding (For Reusable Parameters)
If multiple services need this array parameter, set up a global binding in the _defaults section. This tells Symfony to automatically inject the array into any constructor with a parameter named $securityConfiguration:
services: _defaults: autowire: true autoconfigure: true public: false # Add this binding rule bind: $securityConfiguration: '%security.configuration%' # ... your other services ...
Quick Sanity Checks
- Verify your array parameter is correctly defined in
service.yamlunder theparameterskey:parameters: security.configuration: enabled: true allowed_roles: ['ROLE_USER', 'ROLE_ADMIN'] - Ensure the parameter name in your config matches exactly with the argument name in
App\Class's constructor (it's case-sensitive!).
内容的提问来源于stack exchange,提问作者Rafal Wycislik

