Do you want to know how to Drupal?

Let's Drupal

Plugin API

How to use dependency injection for Plugins in Drupal 9?

Services are very powerful way to make our code reusable. How can we pass service to our plugin in Drupal 9?

For this example we take code of simple plugin EntityLink. It doesn't actually it could be any plugin

use Drupal\views\Plugin\views\field\EntityLink;
use Drupal\views\ResultRow;

/**
 * Field handler to present a link to approval.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("approve_link")
 */
class ApproveLInk extends EntityLink {

  /**
   * {@inheritdoc}
   */
  protected function getEntityLinkTemplate() {
    return 'approve';
  }

  /**
   * {@inheritdoc}
   */
  protected function renderLink(ResultRow $row) {
    $this->options['alter']['query'] = $this->getDestinationArray();
    return parent::renderLink($row);
  }

  /**
   * {@inheritdoc}
   */
  protected function getDefaultLabel() {
    return $this->t('Approve');
  }

}

We don't call constructor for our plugin. In order to pass our service. Let's take current_user service.

First we need implement 

class ApproveLInk extends EntityLink implements ContainerFactoryPluginInterface {

Add create method, where we pass our service

/**
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   * @param array $configuration
   * @param string $plugin_id
   * @param mixed $plugin_definition
   *
   * @return static
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user')
    );
  }

After that add parameters to our constructor

/**
   * @var AccountInterface $account
   */
  protected $account;

  /**
   * @param array $configuration
   * @param string $plugin_id
   * @param mixed $plugin_definition
   * @param \Drupal\Core\Session\AccountInterface $account
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountInterface $account) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->account = $account;
  }