2

How do I inject services in a class that implements an interface.

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;
  }
}

The above code throws an error.

  • 2
    What's the error? You should always include that. – Jaypan Jan 21 '17 at 10:33
11

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.

| improve this answer | |
  • 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. – edwardchiapet May 31 '17 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. – kiamlaluno May 31 '17 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 {

}
| improve this answer | |

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.