Symfony 5.4快速教程自动装配异常:Conference实体无法注入控制器
Symfony控制器自动装配Conference实体报错解决
访问https://127.0.0.1:8000/conference/1时触发错误:
Cannot autowire argument $conference of "App\Controller\ConferenceController::show()": it references class "App\Entity\Conference" but no such service exists.
控制器代码
namespace App\Controller; use App\Entity\Conference; use App\Repository\CommentRepository; use App\Repository\ConferenceRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Twig\Environment; class ConferenceController extends AbstractController { #[Route('/conference/{id}', name: 'conference')] public function show(Environment $twig, Conference $conference, CommentRepository $commentRepository): Response { return new Response($twig->render('conference/show.html.twig', [ 'conference' => $conference, 'comments' => $commentRepository->findBy(['conference' => $conference], ['createdAt' => 'DESC']), ])); } }
当前services.yml配置
services: # default configuration for services in *this* file _defaults: autowire: true # Automatically injects dependencies in your services. autoconfigure: true # Automatically registers your services as commands, event subscribers, etc. # makes classes in src/ available to be used as services # this creates a service per class whose id is the fully-qualified class name App\: resource: '../src/' exclude: - '../src/DependencyInjection/' - '../src/Entity/' - '../src/Kernel.php'
解决步骤
这个错误不是自动装配服务的问题,而是Symfony参数转换器没有正确识别路由参数与实体的映射。实体类不需要注册为服务,services.yml里排除Entity目录的配置是正确的,你需要做以下调整:
方法1:修改路由参数名
将路由中的{id}改为{conference},让参数转换器自动匹配实体:
#[Route('/conference/{conference}', name: 'conference')] public function show(Environment $twig, Conference $conference, CommentRepository $commentRepository): Response { // ... 原有代码 }
方法2:显式指定参数映射
如果想保留{id}参数名,添加MapEntity注解来指定映射关系:
use Symfony\Bridge\Doctrine\Attribute\MapEntity; // ... #[Route('/conference/{id}', name: 'conference')] public function show(Environment $twig, #[MapEntity(id: 'id')] Conference $conference, CommentRepository $commentRepository): Response { // ... 原有代码 }
额外优化
建议使用AbstractController提供的render方法,无需手动注入Twig\Environment,简化代码:
return $this->render('conference/show.html.twig', [ 'conference' => $conference, 'comments' => $commentRepository->findBy(['conference' => $conference], ['createdAt' => 'DESC']), ]);
另外,确保Conference实体的id字段已正确配置ORM主键注解,比如:
use Doctrine\ORM\Mapping as ORM; #[ORM\Entity(repositoryClass: ConferenceRepository::class)] class Conference { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column(type: 'integer')] private ?int $id = null; // ... 其他属性和方法 }
内容的提问来源于stack exchange,提问作者Gunnarius
相关产品推荐
相关产品推荐

