Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 62 ยท Services and the Container

Autowiring and Dependency Injection

See how Symfony autowiring fills constructor arguments from type-hints, how interfaces and aliases choose an implementation, and build a reflection-based autowirer.

In the previous lesson the container built CheckoutService because we told it how, one factory at a time. In a real project that would be tedious, so Symfony does something smarter: it reads your constructor, looks at the type-hint of each parameter and finds the service of that type. This is called autowiring, and it is why a typical Symfony service needs no configuration at all.

This lesson explains constructor injection, how autowiring resolves classes and interfaces, what to do when two implementations compete, and how to inspect the result. The real autowiring happens while Symfony compiles the container, so those examples are read-only. A reflection-based stand-in in plain PHP shows the same algorithm so you can see how little magic there is.

Constructor injection

Dependency injection means a class receives its collaborators instead of creating them. The most common form is constructor injection with promoted properties:

PHP
<?php
namespace App\Service;

use Psr\Log\LoggerInterface;

final class InvoiceSender
{
    public function __construct(
        private readonly InvoiceRenderer $renderer,
        private readonly LoggerInterface $logger,
    ) {
    }

    public function send(int $invoiceId): void
    {
        $html = $this->renderer->render($invoiceId);
        $this->logger->info('Invoice rendered', ['id' => $invoiceId, 'bytes' => strlen($html)]);
    }
}

The class says what it needs and nothing more. In a unit test you pass fakes by hand; in the application the container passes the real objects. Plain-PHP background is in Dependency injection.

You can inject in three more places, and they all use the same autowiring rules:

  • Controller actions: public function show(PriceCalculator $calculator).
  • Other services: any constructor, as above.
  • Methods and properties (setter injection with #[Required]): rarely needed, mostly for optional or circular dependencies.

How autowiring decides

For every constructor parameter, Symfony applies these steps while compiling the container:

  1. Take the parameter's type-hint, for example InvoiceRenderer.
  2. Look for a service whose identifier equals that type. With the App\: resource from services.yaml, every class in src/ is registered under its own class name, so App\Service\InvoiceRenderer matches.
  3. For an interface or abstract class, look for an alias with that name. Symfony creates one automatically when exactly one service implements the interface in your src/ directory.
  4. If nothing matches or the choice is ambiguous, compilation fails with a clear error. Autowiring never guesses at runtime.

Scalar parameters such as string $apiKey cannot be guessed, so you give them explicitly (a bind, an arguments entry or the #[Autowire] attribute, covered in Configuring Services).

flowchart TD
    A["Constructor parameter<br/>with a type-hint"] --> B{"Service with the same<br/>id as the type?"}
    B -->|yes| OK["Inject it"]
    B -->|no| C{"Alias for the type<br/>(interface or abstract)?"}
    C -->|yes| OK
    C -->|no| D{"Default value or<br/>nullable?"}
    D -->|yes| E["Use the default"]
    D -->|no| F["Compile-time error"]

Autowiring is a lookup by type with a short list of fallbacks, resolved before the application runs.

A reflection-based stand-in

PHP's Reflection API can read constructor parameters and their types, which is exactly what autowiring needs. The stand-in below follows the same decision tree as the diagram: class name first, then an alias, then a default value, and a clear error otherwise. The real compiler does this once at build time and writes plain PHP; this stand-in does it on demand.

PHP An autowiring container (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first attempt fails because LoggerInterface is not a class and nothing says which implementation to use; after registering the alias, the whole object graph is built from three type-hints, and the scalar $currency falls back to its default. Real Symfony reports the same kinds of problems, only earlier: when the container compiles, not when a request arrives.

Interfaces and aliases

Coding against an interface lets you swap implementations without touching consumers. If only one class implements your interface, Symfony wires it for you. When there are several, you declare which one is the default with an alias:

YAML
# config/services.yaml
services:
    App\Notification\NotifierInterface: '@App\Notification\SmsNotifier'

Or with an attribute directly on the class, which keeps the decision next to the code:

PHP
<?php
namespace App\Notification;

use Symfony\Component\DependencyInjection\Attribute\AsAlias;

#[AsAlias(NotifierInterface::class)]
final class SmsNotifier implements NotifierInterface
{
    // ...
}

Now every NotifierInterface $notifier parameter receives SmsNotifier. To pick a different one for a single parameter, use #[Autowire(service: ...)]:

PHP
<?php
use App\Notification\EmailNotifier;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

final class AlertService
{
    public function __construct(
        #[Autowire(service: EmailNotifier::class)]
        private NotifierInterface $notifier,
    ) {
    }
}

Named autowiring aliases

Some bundles register several services of one type, for instance two HTTP clients or two cache pools. They also create named aliases so that the parameter name selects one. A parameter HttpClientInterface $githubClient gets the client configured with the scope github. Run php bin/console debug:autowiring http_client to see which names are available. A different-name alias is a feature of the bundle; your own services do not get it unless you declare it with bind or an alias.

When autowiring cannot decide

Common situations and their usual fix:

Situation Typical error Fix
Interface with two implementations "references interface ... but no such service exists" or an ambiguity message Add an alias or #[AsAlias]
Scalar argument (string $apiKey) "Cannot autowire argument ... it has no type-hint or the type is not a class" Use #[Autowire], bind or arguments
Class not in a registered directory "Cannot autowire service ... class does not exist" Check resource/exclude in services.yaml
A circular chain A needs B needs A "Circular reference detected" Break the cycle: extract a third class or inject a lazy service

Autowiring errors are one of Symfony's strengths: they come from cache:clear, lint:container or the first page in development, with the exact service and argument named.

Inspecting the result

Terminal
php bin/console debug:autowiring            # all types you can type-hint
php bin/console debug:autowiring Notifier   # filter by name
php bin/console debug:container App\\Service\\InvoiceSender

The last command lists the arguments Symfony chose for the constructor, which is the quickest way to confirm the wiring when something behaves strangely.

Prefer interfaces for things that have real alternatives (notifiers, payment gateways, storage) and concrete classes for everything else. Creating an interface for every class only adds files.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does autowiring use to choose the object for a constructor parameter?

    Autowiring looks up a service whose identifier matches the type-hint, using aliases for interfaces and abstract classes.
  2. 2. A service has the parameter string $apiKey. What happens with autowiring alone?

    Scalars have no service to look up. You must pass them with #[Autowire], bind or arguments (or give the parameter a default value).
  3. 3. Two classes implement NotifierInterface. How do you tell Symfony which one to inject by default?

    An alias maps the interface name to one implementation. Without it, the container cannot choose and compilation fails.
  4. 4. When are autowiring problems normally reported?

    Symfony resolves the wiring at compile time and fails early with a precise message. Our stand-in resolves lazily only to stay simple.

Summary

  • Constructor injection lets a class declare its dependencies; autowiring fills them from the type-hints.
  • A service id equals its class name when you register src/ with a resource; interfaces need an alias unless there is exactly one implementation.
  • Use #[AsAlias] or an alias entry to choose a default implementation, and #[Autowire(service: ...)] for a single parameter.
  • Scalars, ambiguous interfaces and circular references need explicit configuration or a design change.
  • debug:autowiring and debug:container show what can be injected and what was injected.

Next, learn how to pass values, parameters and environment variables into services in Configuring Services.