Symfony 4.4 事件调度器

Symfony 4.4 Event Dispatcher

我收到以下错误:

Service "event_dispatcher" not found: even though it exists in the app's container, the container inside "App\Controller\RatingApiController" is a smaller service locator that only knows about the "form.factory", "http_kernel", "parameter_bag", "request_stack", "router", "security.authorization_checker", "security.csrf.token_manager", "security.token_storage", "serializer", "session" and "twig" services. Try using dependency injection instead.

我习惯用

 $this->get('event_dispatcher')->dispatch( AverageRatingEvent::NAME, new AverageRatingEvent($rating));

用于调度事件,但 'event_dipatcher' 出现错误我似乎找不到源。

这是我的控制器的一部分:

<?php

namespace App\Controller;

use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ODM\MongoDB\MongoDBException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use App\Document\Rating;
use App\Event\AverageRatingEvent;
use App\Form\Type\RatingType;
use App\Helpers\FormErrorsSerializer;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\Event;

class RatingApiController extends AbstractController
{
    private $documentManager;
    public function __construct(DocumentManager $documentManager)
    {
        $this->documentManager = $documentManager;
    }

class RatingApiController extends AbstractController
{
    private $documentManager;
    public function __construct(DocumentManager $documentManager)
    {
        $this->documentManager = $documentManager;
    }

        
    /**
     * @Route("api/rating/create", name="CreateRating",  methods={"POST"})
     * @param DocumentManager $dm
     * @param Request $request
     * @return RedirectResponse|Response
     * @throws MongoDBException
     */
    public function addRating(Request $request, EventDispatcherInterface $dispatcher)
    {
        $response = [];

        $form = $this->
        createForm(RatingType::class, new Rating() ,array('csrf_protection' => false));  
        

        $request = json_decode($request->getContent(), true);
        
        $form->submit($request);

        if($form->isSubmitted() && $form->isValid())
        {
        
           $rating = $form->getData();

           $this->documentManager->persist($rating);
           $this->documentManager->flush();
           
        //    $event = new AverageRatingEvent($rating);
           $this->get('event_dispatcher')->dispatch( AverageRatingEvent::NAME, new AverageRatingEvent($rating));
        //    $dispatcher->dispatch(AverageRatingEvent::NAME, $event);

}
}

事件调度程序不包含在 AbstractController 容器中。

查看 symfony 文档: 在这里你可以找到一个如何使用事件调度程序的例子: https://symfony.com/doc/4.4/components/event_dispatcher.html