4

How do I inject services in a service?

I am using the following code, but it throws an error.

class RoleNegotiator implements ThemeNegotiatorInterface {

  public static function create(ContainerInterface $interface) {
    return new static(
      $interface->get('router.admin_context')
    );
  }
  public function __construct(RouteMatchInterface $route) {
    $this->route = $route;
  }
}
1
  • 2
    What's the error? You should always include that.
    – Jaypan
    Jan 21, 2017 at 10:33

2 Answers 2

12

You define the necessary services as arguments of the service you implement.

Since you are showing a class that implements ThemeNegotiatorInterface, see the theme.negotiator.default service and the class implementing it, Drupal\Core\Theme\DefaultNegotiator.

Service definition

  theme.negotiator.default:
    class: Drupal\Core\Theme\DefaultNegotiator
    arguments: ['@config.factory']
    tags:
      - { name: theme_negotiator, priority: -100 }

Class constructor

public function __construct(ConfigFactoryInterface $config_factory) {
  $this->configFactory = $config_factory;
}

There isn't any static create() method as in your code.

2
  • 1
    Thanks for this answer. I'm used to implementing ContainerInjectionInterface in my classes whenever I need to inject some services. In what cases would I want to define the services in my *.services.yml versus implementing ContainerInjectionInterface? Thank you. May 31, 2017 at 12:42
  • As far as I can recall, if you aren't replacing a service implemented by another module, you should define your service in the .services.yml file.
    – apaderno
    May 31, 2017 at 15:37
3

You need to implement ContainerInjectionInterface as well to inject the dependency in your class (if its not a service). But if you are creating a new service you can inject it in module.services.yml itself as said by @kiamlaluno in his answer.

class RoleNegotiator implements ThemeNegotiatorInterface, ContainerInjectionInterface {

}

Your Answer

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

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