It is not obvious how to inject a service into a controller in Drupal 8. You actually need to use a create() function to do that.
<?php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\my_module\MyService;
/**
* Class PostController.
*/
class PostController extends ControllerBase {
private $myService;
public static function create(ContainerInterface $container) {
return new static ($container->get('my_module.service'));
}
public function __construct(MyService $my_service) {
$this->myService = $my_service;
}
/**
* Controller main action. Use the service.
*/
public function page() {
$this->myService->doSomething();
}
}
?>