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

Symfony 6多上下文项目控制器构造函数依赖注入失败求助

Symfony 6多上下文项目控制器依赖注入失败问题

错误信息

控制器存在必填构造函数参数,但未在容器中注册。你是否忘记将控制器定义为服务?

问题描述

基于Symfony 6开发多上下文项目(每个上下文有独立内核、路由、服务),尝试向控制器构造函数注入依赖时失败,返回上述错误。

相关配置与代码

Composer.json

{
    "psr-4": {
        "CourtsReservationApp\\Context\\Backoffice\\Backend\\": "context/backoffice/backend/src",
        "CourtsReservationApp\\": ["src"]
    }
}

RandomNumberGenerator 接口

<?php
namespace CourtsReservationApp\Backoffice\Domain;

interface RandomNumberGenerator
{
    public function generate(): int;
}

RandomNumberGenerator 实现类

<?php
declare(strict_types=1);

namespace CourtsReservationApp\Backoffice\Infrastructure;

use CourtsReservationApp\Backoffice\Domain\RandomNumberGenerator;

final class PhpRandomNumberGenerator implements RandomNumberGenerator
{
    public function generate(): int
    {
        return random_int(1, 5);
    }
}

控制器代码

<?php

namespace CourtsReservationApp\Context\Backoffice\Backend\Controller\HealthCheck;

use CourtsReservationApp\Backoffice\Domain\RandomNumberGenerator;
use Symfony\Component\HttpFoundation\JsonResponse;

class HealthCheckGetController
{
    public function __construct(private RandomNumberGenerator $generator)
    {
    }

    public function index()
    {
        return new JsonResponse([
            'success' => true,
            "number" => $this->generator->generate()
        ]);
    }
}

services.yaml

parameters: null
services:
    _defaults:
        autowire: true
        autoconfigure: true
        
    CourtsReservationApp\Context\Backoffice\Backend\Controller\:
        resource: '../src/Controller/'
        tags: ['controller.service_arguments']
        
    CourtsReservationApp\Backend\:
        resource: '../../../../src/*'

BackofficeKernel

<?php
declare(strict_types=1);

namespace CourtsReservationApp\Context\Backoffice\Backend;

use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;

final class BackofficeBackendKernel extends Kernel
{
    use MicroKernelTrait;

    private const CONFIG_EXTS = ".{xml, yaml, yml}";

    public function getProjectDir(): string
    {
        return dirname(__DIR__);
    }

    public function registerBundles(): iterable
    {
        $contents = require $this->getProjectDir() . '/config/bundles.php';
        foreach ($contents as $class => $envs) {
            if ($envs[$this->environment] ?? $envs['all'] ?? false) {
                yield new $class();
            }
        }
    }

    protected function configureRoutes(RoutingConfigurator $routes): void
    {
        $confDir = $this->getProjectDir() . '/config';

        $routes->import($confDir.'/{routes}/'.$this->environment.'/*.yaml');
        $routes->import($confDir.'/{routes}/*.yaml');
    }

    protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader):void
    {
        $container->addResource(new FileResource($this->getProjectDir() . '/config/bundles.php'));
        $container->setParameter('container.dumper.inline_class_loader', true);
        $confDir = $this->getProjectDir() . '/config';

        $loader->load($confDir . '/services' . self::CONFIG_EXTS, 'glob');
        //$loader->load($confDir . '/services_' . $this->environment . self::CONFIG_EXTS, 'glob');
        //$loader->load($confDir . '/services/*' . self::CONFIG_EXTS, 'glob');
    }
}

已尝试操作

  • 执行composer dump-autoload
  • 执行bin/console cache:clear
  • 删除var/cache目录

解决方案

1. 修正services.yaml中的命名空间错误

当前services.yaml里的CourtsReservationApp\Backend\:命名空间与实际代码结构不符,改为CourtsReservationApp\Backoffice\:才能覆盖接口和实现类所在目录:

parameters: null
services:
    _defaults:
        autowire: true
        autoconfigure: true
        
    CourtsReservationApp\Context\Backoffice\Backend\Controller\:
        resource: '../src/Controller/'
        tags: ['controller.service_arguments']
        
    # 修正命名空间,匹配实际代码结构
    CourtsReservationApp\Backoffice\:
        resource: '../../../../src/*'

2. 显式绑定接口到实现类(可选)

为确保Symfony能正确解析接口对应的实现,可在services.yaml中添加显式绑定:

services:
    # ... 保留原有配置 ...
    
    # 绑定RandomNumberGenerator接口到对应的实现类
    CourtsReservationApp\Backoffice\Domain\RandomNumberGenerator:
        class: CourtsReservationApp\Backoffice\Infrastructure\PhpRandomNumberGenerator

3. 重新清理缓存与自动加载

执行以下命令确保配置生效:

bin/console cache:clear
composer dump-autoload

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:15:33