Symfony3.4 Guard认证Autowire注入EntityManager报错求助
Hey there! Let's work through this autowiring error you're hitting with your Guard authenticator. The root issue here is how Symfony 3.4 handles service references and autowiring for Doctrine's EntityManager—here's how to fix it step by step:
1. Use the EntityManagerInterface (Recommended Approach)
Symfony 3.4's autowiring works best with interfaces rather than concrete classes for Doctrine services. The error mentions your constructor is hinting at Doctrine\ORM\EntityManager, but you should switch to its parent interface instead:
- Update your
LoginFormAuthenticatorconstructor to useEntityManagerInterface:// src/AppBundle/Security/LoginFormAuthenticator.php use Doctrine\ORM\EntityManagerInterface; class LoginFormAuthenticator extends AbstractFormLoginAuthenticator { private $em; public function __construct(EntityManagerInterface $em) { $this->em = $em; } // ... rest of your authenticator code }
This tells Symfony to inject the correct EntityManager service, since it's configured to map the interface to the default entity manager service out of the box.
2. Verify Autowiring is Enabled for Your Authenticator
Symfony 3.4 doesn't enable autowiring for all services by default. Make sure your LoginFormAuthenticator is set up to use autowiring in your app/config/services.yml:
# app/config/services.yml services: # Auto-register all services in src/AppBundle (optional but convenient) AppBundle\: resource: '../src/AppBundle/*' exclude: '../src/AppBundle/{Entity,Repository,Tests}' autowire: true autoconfigure: true # Or explicitly configure just your authenticator AppBundle\Security\LoginFormAuthenticator: autowire: true tags: - { name: security.guard.authenticator }
Double-check that autowire: true is present for your service—this is required for Symfony to automatically inject dependencies like the EntityManager.
3. Fallback: Add a Service Alias (If You Want to Keep the Concrete Class)
If you really don't want to switch to the interface, you can create an alias for the EntityManager class in your services config to map it to the correct service ID:
# app/config/services.yml services: # ... Doctrine\ORM\EntityManager: '@doctrine.orm.entity_manager'
This tells Symfony that whenever a constructor hints at the concrete EntityManager class, it should inject the default entity manager service.
4. Double-Check Doctrine Bundle is Enabled
Make sure the Doctrine ORM Bundle is registered in your AppKernel.php—without it, the EntityManager service won't exist at all:
// app/AppKernel.php public function registerBundles() { $bundles = [ // ... new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), // ... ]; return $bundles; }
Once you make these changes, clear your Symfony cache with php bin/console cache:clear (and --env=prod if you're working in production) to ensure the new service config takes effect.
内容的提问来源于stack exchange,提问作者Behzad Lashkari

