Change record status: 
Project: 
Introduced in branch: 
10.2.x
Introduced in version: 
10.2.0
Description: 

Classes that implement \Drupal\Core\DependencyInjection\ContainerInjectionInterface must provide a create() factory method to instantiate the object.

Now that services can be autowired, a trait has been added that provides a generic version of the create() method suitable for most dependency injection constructors.

Previously, a constructor and create() method would be something like this:

  public function __construct(DateFormatterInterface $date_formatter, CacheBackendInterface $cache) {
    $this->dateFormatter = $date_formatter;
    $this->cache = $cache;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('date.formatter'),
      $container->get('cache.default')
    );
  }

Now it is possible to drop the create() method:

  use AutowireTrait;

  public function __construct(
    DateFormatterInterface $date_formatter,
    #[Autowire(service: 'cache.default')]
    CacheBackendInterface $cache
  ) {
    $this->dateFormatter = $date_formatter;
    $this->cache = $cache;
  }

In simple cases, the service can be inferred from the interface name alone. If a service cannot be determined from the interface directly, an exception will be raised, and you can add the #[Autowire] attribute to specify the service ID.

Impacts: 
Module developers

Comments

byrond’s picture

If type hints are not sufficient, and you need to add the #[Autowire] attribute, you must also include the following use statement in your file:

use Symfony\Component\DependencyInjection\Attribute\Autowire;