In Symfony 4.2+ you have to use the package:
composer require symfony/proxy-manager-bridge
otherwiese you get the exception:
Resetting a non-lazy manager service is not supported. Declare the "doctrine.orm.default_entity_manager" service as lazy.
Than you can reset the entityManager like this:
services.yaml:
App\Foo:
- '@doctrine.orm.entity_manager'
- '@doctrine'
Foo.php:
use Doctrine\Bundle\DoctrineBundle\Registry;
use Doctrine\DBAL\DBALException;
use Doctrine\ORM\EntityManagerInterface;
try {
$this->entityManager->persist($entity);
$this->entityManager->flush();
} catch (DBALException $e) {
if (!$this->entityManager->isOpen()) {
$this->entityManager = $this->doctrine->resetManager();
}
}