[英]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.