In Drupal 8, a service is any object managed by the services container. Drupal 8 introduces the concept of services to decouple reusable functionality and makes these services pluggable and replaceable by registering them with a service container. Services are used to perform operations like accessing the database or sending an e-mail. If we need to access a service defined by another (contributed or custom) module, it is always better to check if that service exists. We can check if service is available using following method :
<?php
if (!empty(\Drupal::hasService('path.alias_manager'))) {
  $pathManager = \Drupal::service('path.alias_manager');
}
?>

Reference:

Submitted by ychaugule on