How to resolve ServiceCircularReferenceException?

夙愿已清 提交于 2019-12-07 18:23:30

问题


I wanted to inject the current user into an Entity Listener but I ran into an ServiceCircularReferenceException.

I know there are other questions dealing with this issue, and one mentioned solution was to inject the entire service_container into the listener, which didn't work.

I then stumbled accross a seemingly duplicate question, where the provided accepted answer was to implement a UserCallable. But this again yields in the exact same exception.

Could it be that it is due to my dependency of the FOSUserBUndle?

How can I fix this?

The exception:

[Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException] Circular reference detected for service "doctrine.orm.default_entity_manager", path: "doctrine.orm.default_entity_manager -> doctrine.dbal.default_connection -> h nassetdb.approval_listener -> security.context -> security.authentication.manager -> fos_user.user_provider.username -> fos_user.user_manager".

My UserBundle service.yml entry:

parameters:
    hn_user_callable.class: Hn\UserBundle\Services\UserCallable

hn_user.callable:
    class: %hn_user_callable.class%
    arguments: ["@service_container"]

How I setup my entity listener:

hnassetdb.approval_listener:
    class: %approval_listener.class%
    arguments: ['@hn_user.callable', '@logger']
    tags:
        - { name: doctrine.event_listener, event: onFlush }

The UserCallable:

<?php

namespace Hn\UserBundle\Services;

use Hn\UserBundle\Entity\User;
use Hn\UserBundle\Exception\NoCurrentUserAvailableException;
use Symfony\Component\DependencyInjection\ContainerInterface;

class UserCallable implements UserCallableInterface
{
    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * @return User
     * @throws \Hn\UserBundle\Exception\NoCurrentUserAvailableException
     */

    public function getCurrentUser()
    {
        $currentUser = $this->container->get('security.context')->getToken()->getUser();

        if (!$currentUser instanceof User) {
            throw new NoCurrentUserAvailableException();
        }

        return $currentUser;
    }
}

Relevant part of my listener:

class ApprovalListener extends ContainerAware implements EventSubscriber {

  /**
   * @var \Hn\UserBundle\Entity\User
   */
  protected  $currentUser;
  /**
   * @var \Psr\Log\LoggerInterface
   */
  private $logger;

  public function __construct(UserCallableInterface $userCallable, LoggerInterface $logger)
  {
    $this->currentUser = $userCallable->getCurrentUser();
    $this->logger = $logger;
  }

  ...
}

来源:https://stackoverflow.com/questions/24800289/how-to-resolve-servicecircularreferenceexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!