title: Jersey + HK2 + Grizzly: Proper way to inject EntityManager?
body: <p>I've managed to set up injection (into resource classes) of my own service classes in Jersey, HK2 and a plain GrizzlyServer. (Basically followed <a href="https://github.com/jersey/jersey/blob/master/tests/e2e/src/test/java/org/glassfish/jersey/tests/e2e/server/CustomInjectablesResourceConfigTest.java">this example</a>.)</p>
  
  <p>I'm now curious what the best is to inject JPA EntityManagers into my resource classes? (I'm currently considering one request as one unit of work). One option that I'm currently exploring is to use a <code>Factory&lt;EntityManager&gt;</code> in the following way:</p>
  
  <pre><code>class MyEntityManagerFactory implements Factory&lt;EntityManager&gt; {
  
      EntityManagerFactory emf;
  
      public MyEntityManagerFactory() {
          emf = Persistence.createEntityManagerFactory("manager1");
      }
  
      @Override
      public void dispose(EntityManager em) {
          em.close();
      }
  
      @Override
      public EntityManager provide() {
          return emf.createEntityManager();
      }
  
  }
  </code></pre>
  
  <p>and bind it as follows:</p>
  
  <pre><code>bindFactory(new MyEntityManagerFactory())
          .to(EntityManager.class)
          .in(RequestScoped.class);
  </code></pre>
  
  <p>The problem is that the <code>dispose</code>-method is never invoked.</p>
  
  <p>My questions:</p>
  
  <ol>
  <li>Is this the right approach to injecting EntityManagers in Jersey+HK2?</li>
  <li>If so, how should I make sure my EntityManagers are closed properly?</li>
  </ol>
  
  <p>(I'd rather not depend on heavy weight containers or an extra dependency-injection library just to cover this use case.)</p>