Symfony 4无法自动装配Mailer、Router?依赖注入遇服务不存在报错
Hey there! The error you’re seeing happens because Symfony 4 no longer registers the Symfony\Component\Templating\EngineInterface as a default service—the framework shifted toward directly using Twig-specific services instead of the generic templating interface. Let’s walk through two ways to fix this:
Option 1: Use Twig's Specific Services (Recommended)
Symfony 4 recommends injecting Twig's concrete services directly, which is more explicit and aligns with the framework’s modern practices. You have two solid choices here:
A. Inject Twig\Environment
This is the core Twig service that powers template rendering. Update your constructor like this:
use Swift_Mailer; use Twig\Environment; use Symfony\Component\Routing\RouterInterface; public function __construct(Swift_Mailer $mailer, Environment $twig, RouterInterface $router) { $this->mailer = $mailer; $this->router = $router; $this->twig = $twig; // You can keep the property name as $templating if you prefer }
To render templates, use $this->twig->render('path/to/template.html.twig', $data)—it works exactly like the old EngineInterface method.
B. Inject Symfony\Bridge\Twig\TwigEngine
If you want to stick closer to the original EngineInterface behavior, use Twig’s implementation of that interface:
use Swift_Mailer; use Symfony\Bridge\Twig\TwigEngine; use Symfony\Component\Routing\RouterInterface; public function __construct(Swift_Mailer $mailer, TwigEngine $templating, RouterInterface $router) { $this->mailer = $mailer; $this->router = $router; $this->templating = $templating; }
This preserves your original property names and template rendering workflow.
Option 2: Register EngineInterface as an Alias (If You Must Keep It)
If you really want to retain EngineInterface in your constructor, manually alias it to Twig’s implementation in your config/services.yaml:
services: # Map the interface to the Twig service Symfony\Component\Templating\EngineInterface: alias: Symfony\Bridge\Twig\TwigEngine
After adding this, Symfony will automatically resolve EngineInterface to the TwigEngine instance when injecting dependencies.
A Quick Note on Auto-Configuration
Since you’re using Symfony 4, as long as your custom service lives in the src/ directory, auto-configuration will handle dependency injection automatically—no need to manually define your service in services.yaml unless you have special settings.
内容的提问来源于stack exchange,提问作者Suraj Gusain

