I am trying to create a basic event subscriber, but when I add the services.yml file and attempt to rebuild the cache with drush cr, I get this error.

In Drupal.php line 130:

\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.

If I clear the cache from Drupal, it works fine, but Drush always errors out. If I remove the services file, Drush works fine again.

Has anyone seen this before? I don't want to move forward without resolving this. I have added services and event subscribers in this project before without an issue. I double checked spacing structure, etc.


    class: Drupal\gary_custom\EventSubscriber\CustomEventSubscriber
      - { name: event_subscriber }


namespace Drupal\gary_custom\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;

class CustomEventSubscriber implements EventSubscriberInterface {

   * {@inheritdoc}
  static function getSubscribedEvents() {
    \Drupal::logger('debug')->debug('get sub events');

    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;

   * This method is called whenever the KernelEvents::REQUEST event is
   * dispatched.
   * @param GetResponseEvent $event
  public function checkForRedirection(GetResponseEvent $event) {

I am using Drush 9.4.0.

  • 4
    Have you tried without the logging lines? In the getSubscribedEvents method in particular?
    – Clive
    Mar 5, 2019 at 20:03
  • Wow weird that was totally it thank you. Post your answer when you get a sec @Clive Mar 6, 2019 at 15:59

1 Answer 1


The problem is the logging line in getSubscribedEvents:

\Drupal::logger('debug')->debug('get sub events');

Drupal::logger queries the container for a service, but the container hasn't been set at the point the event subscriber discovery happens.

By the time the event handler is invoked, the container has been initialised, so the logging in checkForRedirection should work fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.