找不到服务:即使它存在于应用程序的容器中

Service not found: even though it exists in the app's container

我有什么:

services.yaml:

app.foo.bar:
    class: App\Foo\Bar
    arguments: #[ ... ]

控制器:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class MyController extends Controller
{
    public function baz(Request $request)
    {
        $this->get('some_bundle.some_service');
    }
}

而且有效。

但是由于 Symfony\Bundle\FrameworkBundle\Controller\Controller 已被弃用,我尝试扩展 Symfony\Bundle\FrameworkBundle\Controller\AbstractController 并且得到了

Service "some_bundle.some_service" not found: even though it exists in the app's container, the container inside "App\Controller\MyController" is a smaller service locator that only knows about the "doctrine", "http_kernel", "parameter_bag", "request_stack", "router", "serializer" and "session" services. Try using dependency injection instead.

我能以某种方式将 get()AbstractController 一起使用吗? AbstractController使用ControllerTrait,不知为什么会报错

symfony4 与以前的版本相比发生了很多变化。您正在使用所有内容,就像在以前的版本中一样。快速解决方案不是 "preferred" 方式,但要开始可以将 public 键从默认 false 更改为 true 在你的 services.yaml 文件中。

更好的方法是将其保留为私有并改用依赖注入。服务的命名也发生了变化(现在只是服务的路径)。请参阅文档 here。对于您的代码,请尝试这些:

// services.yaml

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false

    App\Foo\Bar:
        tags: { ** }

以及具有依赖注入的控制器:

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class MyController extends AbstractController
{
    public function baz(Request $request, Bar $bar)
    {
        $bar->doSomething();
    }
}

关于这些东西(以及更多)有一个很好的教程here