@Override
    public ManagedReference getReference() {
      PersistenceUnitService service =
          (PersistenceUnitService)
              deploymentUnit.getServiceRegistry().getRequiredService(puServiceName).getValue();
      EntityManagerFactory emf = service.getEntityManagerFactory();

      if (!ENTITY_MANAGER_FACTORY_CLASS.equals(
          injectionTypeName)) { // inject non-standard wrapped class (e.g.
                                // org.hibernate.SessionFactory)
        Class extensionClass;
        try {
          // make sure we can access the target class type
          extensionClass = pu.getClassLoader().loadClass(injectionTypeName);
        } catch (ClassNotFoundException e) {
          throw new RuntimeException(
              "couldn't load " + injectionTypeName + " from JPA modules classloader", e);
        }
        // TODO:  when/if jpa supports unwrap, change to
        //   Object targetValueToInject = emf.unwrap(extensionClass);
        // Until jpa supports unwrap on sessionfactory, only support hibernate

        Method getSessionFactory;
        try {
          getSessionFactory = emf.getClass().getMethod("getSessionFactory");
        } catch (NoSuchMethodException e) {
          throw new RuntimeException(
              "Can only inject from a Hibernate EntityManagerFactoryImpl", e);
        }

        Object targetValueToInject = null;
        try {
          targetValueToInject = getSessionFactory.invoke(emf, new Object[0]);
        } catch (IllegalAccessException e) {
          throw new RuntimeException(
              "Couldn't get Hibernate session factory from entity manager", e);
        } catch (InvocationTargetException e) {
          throw new RuntimeException(
              "Couldn't get Hibernate session factory from entity manager", e);
        }
        return new ValueManagedReference(new ImmediateValue<Object>(targetValueToInject));
      }

      return new ValueManagedReference(new ImmediateValue<Object>(emf));
    }
  private ServiceName getPuServiceName(String scopedPuName)
      throws DeploymentUnitProcessingException {

    return PersistenceUnitService.getPUServiceName(scopedPuName);
  }