I have to override pagecache service in order to have some custom validation logic to be executed for anonymous users. The issue is that I have the domain module's service domain.negotiator to be injected into pagecache service, but when I call the domain.negotiator service it is always null no matter what I do. I think it has to do with something with priority. I can confirm the overridden service is being executed.

Code to override PageCache service

   * {@inheritdoc}
  public function alter(ContainerBuilder $container) {
    // Overrides language_manager class to test domain language negotiation.
    $definition = $container->getDefinition('http_middleware.page_cache');
      new Reference('domain.negotiator'),

Overridden service

   * {@inheritdoc}
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE): Response {
    $domain = \Drupal::service('domain.negotiator');
    $x = $this->domainNegotiator->getActiveDomain();
    $currentDomain = \Drupal::service('entity_type.manager')->getStorage('domain')->createHostname();
    $response = parent::handle($request, $type, $catch);
    return $response;

  • 2
    Even if it looks like a service, a middleware is not a Drupal service, it runs outside of the Drupal kernel.
    – 4uk4
    Dec 20, 2021 at 10:31
  • Thanks, @4k4 for replying, Is there any workaround to achieve it. Initially, I was using subscribing to event KERNAL:: REQUEST to add the custom validation logic that needs to run on every single page for anonymous users, but because of drupal caching, Pages were cached and it was not achieveable. Dec 20, 2021 at 12:05
  • 1
    Workaround for what? The page cache is like a reverse proxy caching based on the URL (including domain name and query string by the way). If this is not what you want then uninstall this module and use the dynamic page cache.
    – 4uk4
    Dec 20, 2021 at 12:25
  • What about $request->getHost() or $request->getSchemeAndHttpHost()?
    – leymannx
    Dec 20, 2021 at 19:01
  • @leymannx Still, I would need user service to check which is always showing anonymous users, I tried with event subscriber but when I set the priority to 210, I can't access the service. Dec 21, 2021 at 6:15


Your Answer

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

Browse other questions tagged or ask your own question.