Closed
Description
Symfony version(s) affected: >=5.1.3
Description
When a service is declared as lazy and non-shared, generated code uses $this->factories['service_name'](false);
inside proxy without initialization of $this->factories['service_name']
before.
How to reproduce
class MyClass {}
$container = new ContainerBuilder();
$container->register('non_shared_foo', MyClass::class)->setShared(false)->setLazy(true)->setPublic(true);
$container->compile();
$dumper = new PhpDumper($container);
$dumper->setProxyDumper(new ProxyDumper());
print_r($dumper->dump(['as_files' => false]));
The generated getNonSharedFooService looks like this:
protected function getNonSharedFooService($lazyLoad = true)
{
if ($lazyLoad) {
return $this->createProxy('MyClass_c5258b3', function () {
return \MyClass_c5258b3::staticProxyConstructor(function (&$wrappedInstance, \ProxyManager\Proxy\LazyLoadingInterface $proxy) {
$wrappedInstance = $this->factories['non_shared_foo'](false);
$proxy->setProxyInitializer(null);
return true;
});
});
}
$this->factories['non_shared_foo'] = function ($lazyLoad = true) {
return new \MyClass();
};
return $this->factories['non_shared_foo']();
}
Possible Solution
This bug comes from this commit - symfony/dependency-injection@37d0137 (#37435)
when I change back this
$factoryCode = $definition->isShared() ? ($asFile ? "\$this->load('%s', false)" : '$this->%s(false)') : '$this->factories[%2$s](false)';
to this
$factoryCode = $asFile ? "\$this->load('%s', false)" : '$this->%s(false)';
it works well.