How to Inject Instances into the Container

Version: 2.8
Edit this page

Warning: You are browsing the documentation for Symfony 2.8, which is no longer maintained.

Read the updated version of this page for Symfony 5.3 (the current stable version).

How to Inject Instances into the Container

In some applications, you may need to inject a class instance as service, instead of configuring the container to create a new instance.

For instance, the kernel service in Symfony is injected into the container from within the Kernel class:

1
2
3
4
5
6
7
8
9
10
11
12
13
// ...
abstract class Kernel implements KernelInterface, TerminableInterface
{
    // ...

    protected function initializeContainer()
    {
        // ...
        $this->container->set('kernel', $this);

        // ...
    }
}

Services that are set at runtime are called synthetic services. This service has to be configured in the container, so the container knows the service does exist during compilation (otherwise, services depending on this kernel service will get a "service does not exist" error).

In order to do so, mark the service as synthetic in your service definition configuration:

  • YAML
  • XML
  • PHP
1
2
3
4
5
services:

    # synthetic services don't specify a class
    app.synthetic_service:
        synthetic: true

Now, you can inject the instance in the container using Container::set():

1
2
3
// instantiate the synthetic service
$theService = ...;
$container->set('app.synthetic_service', $theService);
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.