8 – How to check config setting in custom service class with dependency injection?


In a custom Service class, I need to check a config setting.

I’m able to do this using Drupal::config(static::SETTINGS) as documented here: https://www.drupal.org/docs/drupal-apis/configuration-api/working-with-configuration-forms

but Coder complains:

WARNING | Drupal calls should be avoided in classes, use dependency injection instead

What service should I inject here?

I only need to see the immutable config value, I don’t think I need a ConfigFactory.

More info:

When I try to inject the ConfigFactoryInterface, using the pattern I have followed for many other services, I get this error:

Error: Call to undefined method Drupalmy_custom_moduleApiDataPartner::config() in Drupalmy_custom_moduleApiDataPartner->hasDebugPermission()

The code in the hasDebugPermission() method looks like this:

  /**
   * Private function to control whether displaying debug info is permitted.
   *
   * @return bool
   *   TRUE if debugging is permitted for current user in current environment.
   */
  private function hasDebugPermission() {
    $config = $this->config(static::SETTINGS);
    $result = DATA_PARTNER_FORMS_DEBUG
      && $config->get('display_debugging_info')
      && $this->account->hasPermission('debug forms');
    return $result;
  }

And I have declared static::SETTINGS like this:

  /**
   * Config settings.
   *
   * @var string
   */
  private const SETTINGS = 'my_custom_module.settings';

The call to $this->account->hasPermission() works fine after injecting DrupalCoreSessionAccountInterface, but the call to $this->config('my_custom_module.settings')->get('display_debugging_info') does not work after injecting DrupalCoreConfigConfigFactoryInterface.