如何在自定义服务中获取 Tempating 或 Container?

How to get Tempating or Container in custom Service?

我有自定义服务,我想在 Twig 模板中使用它。 在 Symfony < 3 我可以做到:

use Symfony\Component\DependencyInjection\Container;
//...
public function __construct(Container $container) 
{
    $this->container = $container;
}

public function getView()
{
    $this->container->get('templating')->render('default/view.html.twig');
}

但是在 Symfony 3.3 中我有错误:

Cannot autowire service "AppBundle\Service\ViewService": argument "$container" of method "__construct()" references class "Symfony\Component\DependencyInjection\Container" but no such service exists. Try changing the type-hint to one of its parents: interface "Psr\Container\ContainerInterface", or interface "Symfony\Component\DependencyInjection\ContainerInterface".

not good idea to inject whole container。更好的是注入单个依赖项:

use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;

class MyService
{
    private $templating;
    public function __construct(EngineInterface $templating)
    {
        $this->templating = $templating;
    }

    public function getView()
    {
        $this->templating->render('default/view.html.twig');
    }    
}