title: Should I pass doctrine Registry or specific repositories, entity managers to DI container in symfony2?
body: <p>what is the best practice for injecting repositories, entity managers to a service?</p>
  
  <p>I figured I can do it in at least three ways.</p>
  
  <h2>1. Injecting repositories, managers through the constructor</h2>
  
  <p>This way the service can be covered with tests quite easily. All you need is to pass mocked dependencies to the constructor and you're ready.</p>
  
  <pre><code>class TestService
  {
      public function __construct(MyEntityRepository $my, AnotherEntityRepository $another, EntityManager $manager)
      {
          $this-&gt;my = $my;
          $this-&gt;another = $another;
          $this-&gt;manager = $manager;
      }
  
      public function doSomething()
      {
          $item = $this-&gt;my-&gt;find(&lt;...&gt;);
          &lt;..&gt;
          $this-&gt;manager-&gt;persist($item);
          $this-&gt;manager-&gt;flush();
      }
  }
  </code></pre>
  
  <h2>2. Passing just the EntityManager</h2>
  
  <p>This is a bit more difficult to test if you need like 4 repositories from the same manager. I figured this way you have to mock manager's getRepository calls.</p>
  
  <pre><code>class TestService
  {
      public function __construct(EntityManager $manager)
      {
          $this-&gt;manager = $manager;
      }
  
      public function doSomething()
      {
          $item = $this-&gt;manager-&gt;getRepository('my')-&gt;find(&lt;...&gt;);
          &lt;..&gt;
          $this-&gt;manager-&gt;persist($item);
          $this-&gt;manager-&gt;flush();
      }
  }
  </code></pre>
  
  <h2>3. Passing the whole registry</h2>
  
  <p>This way you don't get circular reference exception with doctrine event subscribers, but it's harder to mock everything.</p>
  
  <p>Also this is the only way sensiolabs insights doesn't give me an architectural violation for injecting EntityManager. </p>
  
  <pre><code>class TestService
  {
      public function __construct(RegistryInterface $registry)
      {
          $this-&gt;doctrine = $registry;
      }
  
      public function doSomething()
      {
          $item = $this-&gt;registry-&gt;getManager()-&gt;getRepository('my')-&gt;find(&lt;...&gt;);
          &lt;..&gt;
          $this-&gt;registry-&gt;getManager()-&gt;persist($item);
          $this-&gt;registry-&gt;getManager()-&gt;flush();
      }
  }
  </code></pre>
  
  <p>What is the best practice to do this and why?</p>