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

Symfony 6.3自定义服务自动注入报错:参数需显式配置

Symfony 6.3 自定义Auth服务注入报错解决

我正在开发Symfony 6.3项目,尝试在控制器中调用自定义Auth服务,该服务需要使用.env文件中定义的配置参数,但遇到如下报错:

Cannot autowire service "App\Services\Authentication\Auth": argument "$region" of method "__construct()" has no type-hint, you should configure its value explicitly.


相关代码

服务文件代码

class Auth implements EventSubscriberInterface
{
    /** @var string */
    private $version;

    /** @var string */
    private $region;

    public function __construct(
        $version,
        $region
    ){
        $this->version = $version;
        $this->region = $region;
    }
}

原services.yaml配置

parameters:
    version: '%env(resolve:VERSION)%'
    region: '%env(resolve:REGION)%'

services:
    _defaults:
        autowire: true      
        autoconfigure: true 

    App\Services\Authentication\Auth: ['@api.auth']
    
    api.auth:
        class: App\Services\Authentication\Auth
        arguments:
            $version: "%version%"
            $region: "%region%"

控制器注入代码

public function __construct(
    private Auth $auth
) {
}

解决方案(修改后的services.yaml)

services:
    _defaults:
        autowire: true   
        autoconfigure: true

    api.auth:
        class: App\Services\Authentication\Auth
        arguments:
            $version: "%version%"
            $region: "%region%"

    App\Controller\ApiController:
        arguments: 
            $auth: '@api.auth'

内容的提问来源于stack exchange,提问作者maued

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 00:36:00