Inject EventDispatcher in service doesn't work in production environment - symfony 3.4

1.1k views Asked by At

let's say I have a listener as a service like this

class MyListener
{
     /**
     * @var Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher 
     */
     private $dispatcher;

     function __construct(ContainerAwareEventDispatcher $dispatcher)
     {
        $this->dispatcher = $dispatcher;
     }

     public function onKernelRequest(GetResponseEvent $event)
     {
        //in my logic here I use $this->dispatcher->dispatch(my-own-event)
     }
}

service.yml

ap.my_listener:
        class: my-name-space\MyListener
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
        arguments: ["@debug.event_dispatcher.inner"]

It's work fine in development environment but when I switch to production environment after clearing cache I get this exception: The service "ap.my_listener" has a dependency on a non-existent service "debug.event_dispatcher.inner"

As I pressed by time I just inject all container, so what happened exactly and there is another way to inject Event Dispatcher without retrieve it from container

1

There are 1 answers

2
craigh On BEST ANSWER

you should just inject the event dispatcher and use an interface like

use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class MyListener
{
     /**
     * @var Symfony\Component\EventDispatcher\EventDispatcherInterface 
     */
     private $dispatcher;

     function __construct(EventDispatcherInterface $dispatcher)
     {
        $this->dispatcher = $dispatcher;
     }

     public function onKernelRequest(GetResponseEvent $event)
     {
        //in my logic here I use $this->dispatcher->dispatch(my-own-event)
     }
}

//service.yml
ap.my_listener:
    class: my-name-space\MyListener
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
    arguments: ["@event_dispatcher"]