Skip to content

Shared service instantiated multiple times #49861

Closed as not planned
Closed as not planned
@julienfalque

Description

@julienfalque

Symfony versions affected

5.4.17 to 5.4.21

Description

With a specific dependency graph with circular references, some services will be instanciated twice, e.g. A' → B → A instead of A → B → A. This happens with symfony/dependency-injection since version 5.4.17 up to latest version to date (5.4.21). Downgrading to version 5.4.16 fixes the issue. This seems to be caused by #48791.

How to reproduce

I'm able to reproduce the issue with this graph of objects:

namespace App;

class ServiceA
{
    public function __construct(
        private readonly ServiceB $serviceB,
        private readonly ServiceC $serviceC,
    ) {
    }
}

class ServiceB
{
    /**
     * @param iterable<ServiceC> $servicesC
     */
    public function __construct(
        private readonly iterable $servicesC,
    ) {
    }
}

class ServiceC
{
    private ServiceA $serviceA;
    private ServiceB $serviceB;

    /**
     * @required
     */
    public function setServiceA(ServiceA $serviceA)
    {
        $this->serviceA = $serviceA;
    }

    /**
     * @required
     */
    public function setServiceB(ServiceB $serviceB)
    {
        $this->serviceB = $serviceB;
    }
}
services:
  _defaults:
    autowire: true
    autoconfigure: true
    public: false

  App\ServiceA:

  App\ServiceB:
    $servicesC: !tagged_iterator foo

  App\ServiceC:
    tags:
      - { name: foo }

Inject ServiceA in e.g. a controller and add a breakpoint or echo something in its constructor to see it's instantiated twice.

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