You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony 4构造函数参数Autowire报错求助(Symfony2.8正常)

Fixing "Cannot autowire service" for Array Parameters in Symfony 4

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.yaml under the parameters key:
    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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:21:24