Symfony4+Doctrine MongoDB Bundle报错:找不到UnitOfWork服务
Got it, let's tackle this "UnitOfWork service not found" error you're hitting with Symfony 4 and Doctrine MongoDB Bundle. I've run into this a few times, so here's what to check step by step:
1. Verify the Bundle is Properly Installed & Registered
First, make sure you've got the right bundle version and it's enabled in your Symfony app:
- Check your
composer.jsonfordoctrine/mongodb-odm-bundle— for Symfony 4, you'll need version^3.0(compatible with Doctrine ODM^2.0). If it's missing, run:composer require doctrine/mongodb-odm-bundle "^3.0" - Open
config/bundles.phpand confirm this line exists:Doctrine\Bundle\MongoDBBundle\DoctrineMongoDBBundle::class => ['all' => true],
2. Check Your MongoDB ODM Configuration File
Symfony 4 relies on the config/packages/doctrine_mongodb.yaml file to set up the Document Manager. Make sure this file exists and has valid configuration (adjust values to match your MongoDB setup):
doctrine_mongodb: connections: default: server: '%env(MONGODB_URL)%' options: {} default_database: '%env(MONGODB_DB)%' document_managers: default: auto_mapping: true mappings: App: is_bundle: false type: annotation dir: '%kernel.project_dir%/src/Document' prefix: 'App\Document' alias: App
This tells Symfony where to find your document classes (like UserDocument) and sets up the core services.
3. Clear Symfony's Cache
Cached configuration can often cause service registration issues. Run this command to clear the cache (adjust --env for production if needed):
php bin/console cache:clear --env=dev
4. Correctly Access UnitOfWork (Don't Inject It Directly)
UnitOfWork isn't a standalone service in the Symfony container — you need to get it from the Document Manager. Here's how to do it properly:
- If you're in a controller or service, first inject the Document Manager:
use Doctrine\ODM\MongoDB\DocumentManager; class YourService { private $documentManager; public function __construct(DocumentManager $documentManager) { $this->documentManager = $documentManager; } public function someMethod() { // Get UnitOfWork from the Document Manager $unitOfWork = $this->documentManager->getUnitOfWork(); // Use $unitOfWork as needed } } - Never try to inject
Doctrine\ODM\MongoDB\UnitOfWorkdirectly via constructor or autowiring — it won't work because it's not registered as a service.
5. Verify Dependency Compatibility
If you're still stuck, double-check that all your Doctrine-related packages are compatible with Symfony 4. Run this command to list installed versions:
composer show doctrine/mongodb-odm doctrine/mongodb-odm-bundle
Ensure doctrine/mongodb-odm is ^2.0 and doctrine/mongodb-odm-bundle is ^3.0 — if not, update them with:
composer update doctrine/mongodb-odm doctrine/mongodb-odm-bundle --with-dependencies
内容的提问来源于stack exchange,提问作者Hope

