[英]Symfony: Cannot autowire argument $injectedVar of "Controller:method()": it references class "App\Entity\Entity" but no such service exists
[英]Cannot autowire service "App\Service\MatchCarAdService": argument "$templating" of method
嗨,我正在创建一个服务。 这是代码,
namespace App\Service;
use Symfony\Component\DependencyInjection\ContainerInterface;
use App\Entity\CarAd;
class MatchCarAdService {
protected $mailer;
protected $templating;
public function __construct(ContainerInterface $container, \Swift_Mailer $mailer, $templating) {
$this->container = $container;
$this->mailer = $mailer;
$this->templating = $templating;
}
public function sendMail() {
$message = (new \Swift_Message('Hello Email'))
->setFrom('vimuths@yahoo.com')
->setTo('vimuths@yahoo.com')
->setBody(
$this->templating->render(
// templates/emails/matching-cars.html.html.twig
'emails/matching-cars.html.html.twig', []
), 'text/html'
);
$this->mailer->send($message);
这是services.yml
MatchCarAdService:
class: App\Service\MatchCarAdService
arguments: ['@mailer','@templating']
但我收到这个错误,
无法解析“App\\Controller\\Api\\SearchController()”的参数 $matchService:无法自动装配服务“App\\Service\\MatchCarAdService”:方法“__construct()”的参数“$templating”没有类型提示,您应该配置其价值明确。
现在你的构造函数有 3 个参数,但在参数中你只放了 2 个。
所以有两种可能的解决方案:
在你的 yaml 中配置
MatchCarAdService:
class: App\Service\MatchCarAdService
arguments: ['@container', '@mailer','@templating']
使用带有类型提示的自动连接这取决于您的 Symfony 版本,但将构造函数更改为
public function __construct(ContainerInterface $container, \Swift_Mailer $mailer, Symfony\Component\Templating\EngineInterface; $teplating) {
$this->container = $container;
$this->mailer = $mailer;
$this->templating = $templating;
}
并且您可能必须composer require symfony/templating
才能获得Symfony\\Bundle\\FrameworkBundle\\Templating\\EngineInterface
服务。
还必须在framework
下添加以下配置:
templating:
enabled: true
engines: ['twig']
@M 的回答。 Kebza 解决了您的情况。 但是您可以使这更简单且防错。 只需使用 Symfony 3.3+ 功能。
services:
_defaults:
autowire: true
App\Service\MatchCarAdService: ~
App\Service\CleaningService: ~
App\Service\RentingService: ~
services:
_defaults:
autowire: true
App\:
resource: ../src
这会../src
PSR-4 约定从../src
目录加载App\\
命名空间中的所有服务。
您可以在 Symfony 3.3帖子中如何重构新的依赖注入功能中看到更多示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.