Updated the patch by checking Drupal::hasService().