Skip to content

[DependencyInjection] Target parameter attribute does not work for Services #51565

Closed as not planned
@issamkhadiri1989

Description

@issamkhadiri1989

Symfony version(s) affected

6.3

Description

Hello,

I am having an issue with the #[Target] attribute when using it in services.

According to https://symfony.com/doc/current/service_container/autowiring.html#dealing-with-multiple-implementations-of-the-same-type,

when I have 2 services implementing the same interface i have 2 choices:

  • create an alias from the Interface and use a default service and create a named alias for the other services

  • use the Target attribute.

With the first choice, everything works fine. But with the 2nd choice, I have created a default alias from the interface, then I create another alias to the other service. When I use the alias in some service I got an error

Cannot resolve argument $client of "App\Controller\TwitterController::index()": Cannot autowire service "App\Service\TwitterClient": "#[Target('appTransformerUpper')" on argument "$transformer" of method "__construct()"

Am I doing something wrong ?

How to reproduce

  1. Create an interface
interface TransformerInterface
{
    public function transform(string $input): string;
}
  1. Create 2 services that implement the same interface
class UppercaseTransformer implements TransformerInterface
{
    public function transform(string $input): string
    {
        return \strtoupper($input);
    }
}
class Rot13Transformer implements TransformerInterface
{
    public function transform(string $input): string
    {
        return \str_rot13($input);
    }
}
  1. Create an alias from the interface in services.yaml
App\Utils\TransformerInterface: '@App\Utils\Transformer\Rot13Transformer'

And then, create another alias to the other service (cf the doc)

app.transformer.upper: '@App\Utils\Transformer\UppercaseTransformer'

Use the Interface as a Type-hint in some service (eg. TwitterClient service) like the following

use Symfony\Component\DependencyInjection\Attribute\Target;

class TwitterClient
{
    private TransformerInterface $transformer;

    public function __construct(
        #[Target('app.transformer.upper')]
        TransformerInterface $transformer
    ) {
        $this->transformer = $transformer;
    }
 ...
}

Possible Solution

No response

Additional Context

No response

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