zjm555
zjm555

Reputation: 861

How can I access the symfony Service Container in my Service?

I have created a new Service, and its job involves calling functions on other services that must be loaded by name at runtime. So, I can't pass in a static set of services to my service, I want it to actually be able to call get() on the service container itself. The Symfony docs haven't been helpful for describing how to do this outside of a Controller class where I can just call $this->get(). Anyone know how?

Upvotes: 0

Views: 133

Answers (1)

zizoujab
zizoujab

Reputation: 7800

You have two possible solutions :

1. Inject the service container :

<argument type="service" id="service_container" />

And then in your class :

use Symfony\Component\DependencyInjection\Container;

//...

public function __construct(Container $container, ...) {

2. Extend ContainerAware class

use Symfony\Component\DependencyInjection\ContainerAware;

class YourService extends ContainerAware
{
    public function someMethod($serviceName) 
    {
        $this->container->get($serviceName)->doSomething(); 
        ...
    }
}

Upvotes: 2

Related Questions