Classes that implement \Drupal\Core\DependencyInjection\ContainerInjectionInterface must provide a create() factory method to instantiate the object.
Now that services can be autowired, the PluginBase class has been extended with a generic version of the create() method suitable for most plugins with dependency injection.
Previously, a constructor and create() method would be something like this:
public function __construct(
array $configuration, $plugin_id,
$plugin_definition,
EntityTypeManagerInterface $entity_type_manager,
BlockManagerInterface $block_manager
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->blockManager = $block_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
$container->get('plugin.manager.block')
);
}
Now it is possible to drop the create() method:
public function __construct(
array $configuration, $plugin_id,
$plugin_definition,
#[Autowire(service: 'entity_type.manager')]
EntityTypeManagerInterface $entity_type_manager,
BlockManagerInterface $block_manager
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->blockManager = $block_manager;
}
Make sure the plugin implements Drupal\Core\Plugin\ContainerFactoryPluginInterface to proceed with autowiring.
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.