use Drupal\Core\DependencyInjection\ContainerInjectionInterface; use Symfony\Component\DependencyInjection\ContainerInterface; class MyClass implements ContainerInjectionInterface { protected $container; public function __construct(ContainerInterface $container) { $this->container = $container; } public static function create(ContainerInterface $container) { return new static($container->get('my_service')); } public function myMethod() { $service = $this->container->get('my_other_service'); // Do something with the service. } }
$container = \Drupal::getContainer(); $my_service = $container->get('my_service'); $my_service->doSomething();In this example, we retrieve the current container instance using the static \Drupal::getContainer() method. We then retrieve a service named "my_service" from the container and execute a method on it. Package/Library: Drupal\Core