Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular reference detected for service "security.context"

I tried to inject the templating service and this is what I get.

<service id="myproject_notification.service.mail" class="%myproject_notification.service.mail.class%">
    <argument type="service" id="mailer" />
    <argument type="service" id="templating" />
</service>

2014-06-10 12-37-10

If I comment, or remove, the templating service from the dependency, everything is working well. I saw old issues about that, but it seems I'm the only one at the moment experiencing this. Am I doing something wrong?

Composer.json

"symfony/symfony": "~2.4",
"twig/extensions": "~1.0",
"symfony/assetic-bundle": "~2.3",
"symfony/swiftmailer-bundle": "~2.3",
"symfony/monolog-bundle": "~2.4",
"sensio/distribution-bundle": "~2.3",
"sensio/framework-extra-bundle": "~3.0",
"sensio/generator-bundle": "~2.3",
"incenteev/composer-parameter-handler": "~2.0",

Composer.lock

"name": "symfony/symfony",
"version": "v2.5.0",
...
"name": "twig/twig",
"version": "v1.15.1",
like image 446
AlixB Avatar asked Jun 10 '14 10:06

AlixB


2 Answers

You should always try to avoid injecting container directly to your services.

I think the best possible solution to the «circular reference» problem as well as to possible performance issues, would be to use «Lazy Services» feature available starting from Symfony 2.3.

Just mark you dependency as lazy in your service container configuration and install ProxyManager Bridge (look for details in Lazy Services documentation above).

I hope that helps, cheers.

like image 84
Slava Fomin II Avatar answered Sep 25 '22 03:09

Slava Fomin II


This solution is a quick way to fix the problem. This can be avoided, please read comments.

For this particular case it may be best to inject the ServiceContainer into your service. As it seems that you are experiencing an edge case, where the security.context is already injected into some templating services (e.g. helpers), which then in your example is injected back (indirectly) to the security.context.

Try this:

<service id="myproject_notification.service.mail" class="%myproject_notification.service.mail.class%">
    <argument type="service" id="service_container" />
</service>

And in your class's constructor, use it as follows:

class YourMailerClass
{
    protected $container; 

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

    public function sendMail()
    {
       $mailer = $this->container->get('mailer');
       $templating = $this->container->get('templating');
    }

}

See this conversation between the Symfony Core developers about the same problem: https://github.com/symfony/symfony/issues/2347

For most cases injecting the service container is not advised for several reasons.

like image 23
Debreczeni András Avatar answered Sep 24 '22 03:09

Debreczeni András