Circular reference detected for service "security.context"

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.


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.