How to Inject Instances into the Container

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. use Symfony\Component\HttpKernel\KernelInterface;
  3. use Symfony\Component\HttpKernel\TerminableInterface;
  4. abstract class Kernel implements KernelInterface, TerminableInterface
  5. {
  6. // ...
  7. protected function initializeContainer(): void
  8. {
  9. // ...
  10. $this->container->set('kernel', $this);
  11. // ...
  12. }
  13. }

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

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

  • YAML

    1. # config/services.yaml
    2. services:
    3. # synthetic services don't specify a class
    4. app.synthetic_service:
    5. synthetic: true
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <!-- synthetic services don't specify a class -->
    9. <service id="app.synthetic_service" synthetic="true"/>
    10. </services>
    11. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. return function(ContainerConfigurator $configurator) {
    4. $services = $configurator->services();
    5. // synthetic services don't specify a class
    6. $services->set('app.synthetic_service')
    7. ->synthetic();
    8. };

Now, you can inject the instance in the container using [Container::set()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/DependencyInjection/Container.php "Symfony\Component\DependencyInjection\Container::set()"):

  1. // instantiate the synthetic service
  2. $theService = ...;
  3. $container->set('app.synthetic_service', $theService);

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.