Multiple entity managers in Symfony 3.3 seams to not work as service arguments Multiple entity managers in Symfony 3.3 seams to not work as service arguments symfony symfony

Multiple entity managers in Symfony 3.3 seams to not work as service arguments


Recently I had a similar issue. The comment of @dbrumann gave me a good clue for resolve it. I used the next approach:

  1. If you use the console command debug:autowiring you will see there is a service aliased as doctrine.

    Doctrine\Common\Persistence\ManagerRegistry alias to doctrine
  2. You can get access to that service in your target class by type-hinting, put the name of the service class (or interface) as argument in the constructor of your target class.

  3. Now you can access all the methods of the service in your target class, by using the method getManager() you will get any of your managers:

    use Doctrine\Common\Persistence\ManagerRegistry;$protected $managerRegistry;public function __construct(ManagerRegistry $managerRegistry){    $this->managerRegistry = $managerRegistry;}public function foo(){    // asuming your managers names are default and second    $firstManager = $this->managerRegistry->getManager('default');    $secondManager = $this->managerRegistry->getManager('second');}


So you defined a service named DatabaseRepository that exists in two variations. At one point it receives the 'client' entity manager, and at another point it receives 'user' entity manager?

I think it always returns you the 'client' manager most probably because that is the first time the service has been defined for the service container. It does not matter what you define it afterwards in the same .yml code.

Now, there is a big "why" rhetoric question for you. Why didn't you define two service classes, each for particular manager? If you really had to do it that way, that indicates some serious design problems in the remaining code of your Project.

Another suggestion: Do name your classes somewhat more descriptive. An entity manager and repository class certainly do something about a database. Naming classes, properties, variables in a proper way I find to be one of the most challenging part of the work, but it makes our lives easier.

Btw. Avoid passing entire container as service parameter:

arguments: ['@service_container',

because it's too expensive resources wise.