Symfony+API Platform下自动注入Repository服务不存在问题求助
Windows Docker环境下Symfony/API Platform自动装配Repository失败的环境相关问题
问题背景
- 环境差异:4名开发者中,3名使用官方最新Docker的Windows环境均触发此Bug,Mac环境无任何问题
- 触发时机:分支开发原本正常,PHPUnit测试可正常运行;创建新实体(生成实体及对应Repository文件)后,执行迁移、创建实体、清缓存、PHPUnit测试等任意命令均报错
错误信息
Cannot autowire service "App\Command\CreateActionsCommand": argument "$roleRepository" of method "__construct()" references class "App\Repository\RoleRepository" but no such service exists.
已做检查与调试现象
- 对照Doctrine文档确认
RoleRepository代码无问题 - 检查
services.yaml,自动装配配置正确,Repository类应被正常识别 - 奇怪现象:手动删除任意一个Repository文件后,所有命令立即恢复正常
RoleRepository代码
<?php namespace App\Repository; use App\Entity\Role; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; /** * @method Role|null find($id, $lockMode = null, $lockVersion = null) * @method Role|null findOneBy(array $criteria, array $orderBy = null) * @method Role[] findAll() * @method Role[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class RoleRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, Role::class); } }
排查与解决建议
检查Docker容器内文件名大小写
Windows文件系统大小写不敏感,挂载到Docker容器后可能出现类名与文件名不匹配(比如RoleRepository.php被识别为小写)。进入容器查看src/Repository目录下的实际文件名,确保与类名完全一致。强制清理所有缓存并同步文件系统
Windows Docker挂载可能存在文件同步延迟,执行以下命令清理缓存:
php bin/console cache:clear --env=dev php bin/console cache:clear --env=test rm -rf var/cache/*
同时检查docker-compose.yml中挂载目录的consistency配置,设置为consistent确保文件变更及时同步到容器内。
- 验证Symfony自动装配规则
确认config/services.yaml中的基础配置正确,Repository目录未被排除在自动装配外:
App\: resource: '../src/' exclude: - '../src/DependencyInjection/' - '../src/Entity/' - '../src/Kernel.php'
临时关闭PHP opcache
若容器内开启了opcache,Windows挂载的文件变更可能无法触发缓存更新。临时修改php.ini关闭opcache,或重启PHP-FPM服务后测试。检查新创建实体的语法与元数据
新实体的语法错误、命名空间错误可能导致Doctrine无法正确加载所有Repository类,仔细检查新实体文件的内容。
内容的提问来源于stack exchange,提问作者Cortodev
相关产品推荐
相关产品推荐

