Symfony get a service from the container without DI #54805
Replies: 2 comments
-
Hi, It seems like you try to inject the container into your current command (EyElasticIndexAllDbCommand), am I right? Maybe you can achieve what you need by creating a CompilerPass ? and if you don't want to make this "new" service definitions available by DI, make them private, tag them, and use a service locator in order to retrieve those into your command. Hope it helps |
Beta Was this translation helpful? Give feedback.
-
If I understand correctly, I think you need a factory. Since Symfony DI is based on the Hollywood Principle (don't call us, we'll call you), you have to create a new service in your bundle that will act as a factory. And then in this factory, you can create your service the way you want. More info on https://symfony.com/doc/6.4/service_container/factories.html |
Beta Was this translation helpful? Give feedback.
-
I am currently working on a command in a bundle (symfony version: 6.4) where i need to get the instance of a service without the possibility of injecting the service. I only have the classname of the service in a variable as follows:
This code is returning an error:
Cannot autowire service "Eyrolles\Intranet\ElasticBundle\Command\EyElasticIndexAllDbCommand": argument "$container" of method "__construct()" references class "Symfony\Component\DependencyInjection\ContainerBuilder" but no such service exists.
I cannot just instantiate the service cause it would be too complicated as i have like 30 services like these and they all have injected dependencies. The easiest would be to add the service to the container an retrieve an instance of the service from the container.
The services could be private or public, synthetic or not, lazy or not, i cannot know beforehand.
How can i achieve this at lowest cost.
Beta Was this translation helpful? Give feedback.
All reactions