Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages showcasing Symfony with Docker, APIs, queues & async tasks, Webpack, SPAs, etc.


You are browsing the documentation for Symfony 2.6 which is not maintained anymore.

Consider upgrading your projects to Symfony 5.2.

How to Inject Instances into the Container

2.6 version

How to Inject Instances into the Container

When using the container in your application, you sometimes need to inject an instance instead of configuring the container to create a new instance.

For instance, if you’re using the HttpKernel component with the DependencyInjection component, then the kernel service is injected into the container from within the Kernel class:

// ...
abstract class Kernel implements KernelInterface, TerminableInterface
    // ...
    protected function initializeContainer()
        // ...
        $this->container->set('kernel', $this);

        // ...

The kernel service is called a synthetic service. 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 exists” error).

In order to do so, you have to use Definition::setSynthetic():

use Symfony\Component\DependencyInjectino\Definition;

// synthetic services don't specify a class
$kernelDefinition = new Definition();

$container->setDefinition('your_service', $kernelDefinition);

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

$yourService = new YourObject();
$container->set('your_service', $yourService);

$container->get('your_service') will now return the same instance as $yourService.

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