Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

What do I have:

services.yaml:

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

Controller:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

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

And it works.

But as Symfony\Bundle\FrameworkBundle\Controller\Controller is deprecated, I've tried to extend Symfony\Bundle\FrameworkBundle\Controller\AbstractController and I got

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.

Can I use get() somehow with AbstractController? AbstractController uses ControllerTrait, I wonder why the error takes place.

like image 880
Tarasovych Avatar asked May 27 '19 12:05

Tarasovych


1 Answers

A lot of things changed in symfony4 vs previous versions. You are using everything as if in a previous version. The quick solution is not the "preferred" way, but to start can change the public key from the default false to true in your services.yaml file.

A better way is to leave it private and use dependency injection instead. The naming of the service has changed as well (now just the path of the service). See the docs here. For your code, try these:

// services.yaml

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

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

And the controller with dependence injection:

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

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

There's a nice tutorial about these things (and more) here.

like image 116
ehymel Avatar answered Nov 03 '22 01:11

ehymel