Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[DI] The generated code for lazy non-shared services doesn't work  #38327

Closed
@surikman

Description

@surikman

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions