title: Symfony dependency injection in twig extension
body: <p>Ok, I was trying to create twig extension with dependencies on other service <em>(security.context)</em> and got some troubles. So, here is my service declaration:</p>
  
  <pre><code>acme.twig.user_extension:
          class: Acme\BaseBundle\Twig\UserExtension
          arguments: ["@security.context"]
          tags:
              - { name: twig.extension }
  </code></pre>
  
  <p>and here's my class</p>
  
  <pre><code>// acme/basebundle/twig/userextension.php
  
  namespace Acme\BaseBundle\Twig;
  
  use Symfony\Component\Security\Core\SecurityContext;
  use Acme\UserBundle\Entity\User;
  
  class UserExtension extends \Twig_Extension
  {
  
      protected $context;
  
      public function __construct(SecurityContext $context){
          $this-&gt;context = $context;
      }
  
      public function getFunctions()
      {
          return array(
              'getAbcData' =&gt; new \Twig_SimpleFunction('getAbcData', $this-&gt;getAbcData()),
          );
      }
  
      public function getAbcData()
      {
          if ( !is_object($user = $this-&gt;context-&gt;getToken()-&gt;getUser()) || !$user instanceof User){ return null; }
          return array(
              'data_array'   =&gt; $user-&gt;getData(),
          );
      }
  
      public function getName()
      {
          return 'user_extension';
      }
  }
  </code></pre>
  
  <p>Finally, I have an error:</p>
  
  <pre><code>FatalErrorException: Error: Call to a member function getUser() on a non-object in \src\Acme\BaseBundle\Twig\UserExtension.php line 27
  </code></pre>
  
  <p>I guess that <em>security.context</em> service is not initialized yet, then i get an error.
  Could anyone tell, please, is there are ways to load service manually, or any better solutions for an issue?
  Thanks a lot.</p>
  
  <hr>
  
  <p><em>I use Symfony 2.5.*</em></p>
  
  <p>UPD:</p>
  
  <p>I've also found this notice in symfony docs</p>
  
  <blockquote>
    <p>Keep in mind that Twig Extensions are not lazily loaded. This means that there's a higher chance that you'll get a CircularReferenceException or a ScopeWideningInjectionException if any services (or your Twig Extension in this case) are dependent on the request service. For more information take a look at How to Work with Scopes.
    Actually, I have no idea about how to do it correct..</p>
  </blockquote>