如何修复Sylius中「无法自动注入服务:参数引用类但无此服务」错误
修复Sylius 1.11中CampaignRepository自动注入错误的方案
错误原因
问题出在仓库的继承逻辑与Sylius资源配置不匹配:你引用了Doctrine的ServiceEntityRepository注释,但实际继承的是Sylius的EntityRepository(来自ResourceBundle),且未按Sylius的资源规则注册服务,导致Symfony无法自动注入仓库构造所需的ClassMetadata依赖。
具体修复步骤
1. 修正Repository的继承与注释
将仓库的注释和继承统一为Sylius规范,移除无关的Doctrine仓库引用:
<?php namespace App\Repository; use App\Entity\Campaign; use Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository; /** * @extends EntityRepository<Campaign> * * @method Campaign|null find($id, $lockMode = null, $lockVersion = null) * @method Campaign|null findOneBy(array $criteria, array $orderBy = null) * @method Campaign[] findAll() * @method Campaign[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class CampaignRepository extends EntityRepository { }
2. 注册Sylius资源映射
在config/packages/sylius_resource.yaml中添加Campaign的资源配置,让Sylius自动管理仓库服务:
sylius_resource: resources: app.campaign: classes: model: App\Entity\Campaign repository: App\Repository\CampaignRepository
3. 确认实体ORM映射正确
检查App\Entity\Campaign的注释,确保Doctrine和Sylius能识别该实体:
<?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; use Sylius\Component\Resource\Model\ResourceInterface; /** * @ORM\Entity(repositoryClass=App\Repository\CampaignRepository::class) * @ORM\Table(name="app_campaign") */ class Campaign implements ResourceInterface { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private ?int $id = null; public function getId(): ?int { return $this->id; } // 其他实体字段与方法 }
4. 清理缓存并验证服务
执行缓存清理命令:
php bin/console cache:clear
验证仓库服务是否正确注册:
php bin/console debug:container App\Repository\CampaignRepository
若输出显示服务已正常定义,即可回到控制器测试自动注入功能。
内容的提问来源于stack exchange,提问作者nstCactus
相关产品推荐
相关产品推荐

