首页 > 解决方案 > 为什么我可以自动装配 EntityManagerInterface 但不能自动装配 UserInterface

问题描述

我编写了使用 EntityManagerInterface 的简单服务并且它正在工作但是当我以类似的方式尝试添加 UserInterface 时,我得到:

AutowiringFailedException 无法自动连接服务“AppBundle\Service\Pricer”:方法“__construct()”的参数“$user”引用接口“Symfony\Component\Security\Core\User\UserInterface”,但不存在此类服务。它不能自动注册,因为它来自不同的根命名空间。

我的代码是:

namespace AppBundle\Service;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class Pricer
{
    private $em;
    private $user;

    public function __construct(EntityManagerInterface $em, UserInterface $user)
    {
        $this->em = $em;
        $this->user = $user;
    }
}

当我只有 EntityManagerInterface 作为参数时它正在工作(我可以获得 Repository 并进行一些查找查询)。我的错误在哪里?

标签: symfonysymfony-3.4

解决方案


基本上是因为 Doctrine ORM 提供了一个默认实现EntityManagerInterface(也就是说EntityManager,你可以在这里查看),而 Symfony 没有提供UserInterface. 这背后的原因UserInterface是它描述了模型实体的合同/公共 api,而不是服务,因此这不适合服务注入的概念。


推荐阅读