In place of Factory<T>.dispose(T)
, registering with the injectable CloseableService
may do most of what you want. A Closeable
adapter will be required. CloseableService
closes()
all registered resources upon exiting the request scope.
class MyEntityManagerFactory implements Factory<EntityManager> {
private final CloseableService closeableService;
EntityManagerFactory emf;
@Inject
public MyEntityManagerFactory(CloseableService closeableService) {
this.closeableService = checkNotNull(closeableService);
emf = Persistence.createEntityManagerFactory("manager1");
}
@Override
public void dispose(EntityManager em) {
em.close();
}
@Override
public EntityManager provide() {
final EntityManager em = emf.createEntityManager();
closeableService.add(new Closeable() {
public final void close() {
em.close();
}
});
return em;
}
}