1

I wrote simple Service which is using EntityManagerInterface and it's working but when I try in similar way add UserInterface I get:

AutowiringFailedException Cannot autowire service "AppBundle\Service\Pricer": argument "$user" of method "__construct()" references interface "Symfony\Component\Security\Core\User\UserInterface" but no such service exists. It cannot be auto-registered because it is from a different root namespace.

My code is:

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;
    }
}

It's working when I have only EntityManagerInterface as argument (I can get Repository and make some find queries). Where is my mistake?

Lukaszy
  • 191
  • 17

1 Answers1

6

Basically because Doctrine ORM has provided a default implementation for EntityManagerInterface (that is EntityManager, you can check it out here) whereas Symfony didn't with UserInterface. The reason behind this is that UserInterface is something that describes a contract/public api of a model entity, not a service so this won't suit the concept of service injection.

DonCallisto
  • 29,419
  • 9
  • 72
  • 100
  • So the good way is to pass User object via method's argument directly to service where I need it? Of course I'm going to improve my knowledge about concept of service injection. – Lukaszy May 08 '18 at 09:03
  • 1
    Check this for how to get the current user (especially the second answer): https://stackoverflow.com/questions/36870272/how-to-get-the-current-logged-user-in-a-service – Tobias Xy May 08 '18 at 09:12