How do I leverage dependency injection for drupal 8 when invoking my module.install->hook_install() mehtod?

Or do I have to use \Drupal:: method at this point?

  • You don't. You have to call services through \Drupal::service or applicable call when in procedural code.
    – Kevin
    Jul 23 '17 at 19:40

Yes, for procedural code in hooks you have to use the static service container wrapper \Drupal. Either to get a service or to use one of the predefined static functions. See for example:


 * Implements hook_install().
function shortcut_install() {
  // Theme settings are not configuration entities and cannot depend on modules
  // so to set a module-specific setting, we need to set it with logic.
  if (\Drupal::service('theme_handler')->themeExists('seven')) {
    \Drupal::configFactory()->getEditable('seven.settings')->set('third_party_settings.shortcut.module_link', TRUE)->save(TRUE);
  • Cool, that is what I thought, I just wanted to make sure my intuition was correct. It's nice to know I'm not going insane.
    – lilott8
    Jul 23 '17 at 19:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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