Closed
Description
In some cases the order in which services are retrieved (and thus constructed) from the ContainerBuilder matter. I've included an example where the order in which services are retrieved make the difference between getting the service as defined and triggering a Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
.
Reproduction code, this works as 'expected', resulting in both a Foo
and Bar
object in their respective variables.
<?php
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
$containerBuilder = new ContainerBuilder();
$definition = new Definition(Foobar::class, [new Reference('foo')]);
$containerBuilder->setDefinition('foobar', $definition);
$definition = new Definition(Foo::class, [new Reference('bar')]);
$containerBuilder->setDefinition('foo', $definition);
$definition = new Definition(Bar::class);
$definition->addMethodCall('addFoobar', [new Reference('foobar')]);
$containerBuilder->setDefinition('bar', $definition);
$bar = $containerBuilder->get('bar');
$foo = $containerBuilder->get('foo');
This code triggers a ServiceCircularReferenceException
.
<?php
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
$containerBuilder = new ContainerBuilder();
$definition = new Definition(Foobar::class, [new Reference('foo')]);
$containerBuilder->setDefinition('foobar', $definition);
$definition = new Definition(Foo::class, [new Reference('bar')]);
$containerBuilder->setDefinition('foo', $definition);
$definition = new Definition(Bar::class);
$definition->addMethodCall('addFoobar', [new Reference('foobar')]);
$containerBuilder->setDefinition('bar', $definition);
$foo = $containerBuilder->get('foo');