Skip to content
Advertisement

How do I get a service from the container directly, if I didn’t/couldn’t inject the service using DI?

I have a part of code where I’m injecting two services $checker and $paginator by dependency injection. It works perfectly:

JavaScript

Below the configuration on services.yaml file:

JavaScript

But I’d like to inject for some reasons service by method:

JavaScript

But it doesn’t work. In previous versions Symfony like 3.4 it used to.

I’m receiving an error:

Service “checker” not found: event though it exists in the app’s container, the container inside “AppControllerDefaultController” is a smaller service locator that only knows about the “http_kernel”, “parameter_bag”, “request_stack”, “router”, “session”, and “twig” services. Try using dependency injection instead.

How should I solve this?

Advertisement

Answer

You need to add your dependencies so the service locator can find them.

Add a method getSubscribedServices() to your controller class:

JavaScript

If your controller class extends AbstractController you can simply do:

JavaScript

If you want to do it in another type of class (e.g. a service that doesn’t extend AbstractController), then you need to declare that your service implements the ServiceSubscriberInterface.

JavaScript

… and you would be able to do the same than you in the controller earlier.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement