Drupal 8 FieldFormatter inject dependencies

Found a nice example in Workflow module

<?php

namespace Drupal\workflow\Plugin\Field\FieldFormatter;

use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\workflow\Entity\WorkflowManager;
use Drupal\workflow\Entity\WorkflowState;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a default workflow formatter.
 *
 * @FieldFormatter(
 *   id = "workflow_default",
 *   module = "workflow",
 *   label = @Translation("Workflow form"),
 *   field_types = {
 *     "workflow"
 *   },
 *   quickedit = {
 *     "editor" = "disabled"
 *   }
 * )
 */
class WorkflowDefaultFormatter extends FormatterBase implements 
ContainerFactoryPluginInterface {

  /**
   * The workflow storage.
   *
   * @var \Drupal\workflow\Entity\WorkflowStorage
   */
  protected $storage;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The  render controller.
   *
   * @var \Drupal\Core\Entity\EntityViewBuilderInterface
   */
  protected $viewBuilder;

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity form builder.
   *
   * @var \Drupal\Core\Entity\EntityFormBuilderInterface
   */
  protected $entityFormBuilder;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, 
array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['label'],
      $configuration['view_mode'],
      $configuration['third_party_settings'],
      $container->get('current_user'),
      $container->get('entity.manager'),
      $container->get('entity.form_builder')
    );
  }

  /**
   * Constructs a new WorkflowDefaultFormatter.
   *
   * @param string $plugin_id
   *   The plugin_id for the formatter.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The definition of the field to which the formatter is associated.
   * @param array $settings
   *   The formatter settings.
   * @param string $label
   *   The formatter label display setting.
   * @param string $view_mode
   *   The view mode.
   * @param array $third_party_settings
   *   Third party settings.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
   *   The entity manager
   * @param \Drupal\Core\Entity\EntityFormBuilderInterface 
$entity_form_builder
   *   The entity form builder.
   */
  public function __construct($plugin_id, $plugin_definition, 
FieldDefinitionInterface $field_definition, array $settings, $label, 
$view_mode, array $third_party_settings, AccountInterface $current_user, 
EntityTypeManagerInterface $entity_manager, EntityFormBuilderInterface 
$entity_form_builder) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, 
$settings, $label, $view_mode, $third_party_settings);
    $this->viewBuilder = 
$entity_manager->getViewBuilder('workflow_transition');
    $this->storage = $entity_manager->getStorage('workflow_transition');
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entity_manager;
    $this->entityFormBuilder = $entity_form_builder;
  }

  /**
   * {@inheritdoc}
   *
   * N.B. A large part of this function is taken from 
CommentDefaultFormatter.
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $output = [];

    $field_name = $this->fieldDefinition->getName();
    $entity = $items->getEntity();
    $entity_type = $entity->getEntityTypeId();

    $user = \Drupal::currentUser(); // @todo #2287057: OK?
    // @todo: Perhaps global user is not always the correct user.
    // E.g., on ScheduledTransition->execute()? 
But this function is mostly used in UI.

    $current_sid = WorkflowManager::getCurrentStateId($entity, $field_name);
    /* @var $current_state WorkflowState */
    $current_state = WorkflowState::load($current_sid);

    // First compose the current value with the normal formatter 
from list.module.
    $elements = workflow_state_formatter($entity, $field_name, $current_sid);

    // The state must not be deleted, or corrupted.
    if (!$current_state) {
      return $elements;
    }

    // Check permission, so that even with state change rights,
    // the form can be suppressed from the entity view (#1893724).
    $type_id = $current_state->getWorkflowId();
    if (!\Drupal::currentUser()->
hasPermission("access $type_id workflow_transition form")) {
      return $elements;
    }

    // Workflows are added to the search results and search index by
    // workflow_node_update_index() instead of by this formatter, so don't
    // return anything if the view mode is search_index or search_result.
    if (in_array($this->viewMode, ['search_result', 'search_index'])) {
      return $elements;
    }

    if ($entity_type == 'comment') {
      // No Workflow form allowed on a comment display.
      // (Also, this avoids a lot of error messages.)
      return $elements;
    }

    // Only build form if user has possible target state(s).
    if (!$current_state->showWidget($entity, $field_name, $user, FALSE)) {
      return $elements;
    }

    // Remove the default formatter. We are now building the widget.
    $elements = [];

    // BEGIN Copy from CommentDefaultFormatter
    $elements['#cache']['contexts'][] = 'user.permissions';
    // Add the WorkflowTransitionForm to the page.
    $output['workflows'] = 
WorkflowManager::getWorkflowTransitionForm($entity, $field_name);

    // Only show the add workflow form if the user has permission.
    $elements['#cache']['contexts'][] = 'user.roles';
    // Do not show the form for the print view mode.
    $elements[] = $output + [
      '#workflow_type' => $this->getFieldSetting('workflow_type'),
      '#workflow_display_mode' => $this->getFieldSetting('default_mode'),
      'workflows' => [],
      ];
    // END Copy from CommentDefaultFormatter

    return $elements;
  }

  /**
   * Retrieves the entity form builder.
   *
   * @return \Drupal\Core\Entity\EntityFormBuilderInterface
   *   The entity form builder.
   */
  protected function entityFormBuilder() {
    if (!$this->entityFormBuilder) {
      $this->entityFormBuilder = 
$this->container()->get('entity.form_builder');
    }
    return $this->entityFormBuilder;
  }

}
Drupal 8 FieldFormatter inject dependencies

Dependency Injection and Route Information in a block, drupal 8.

For Route Information user this

$nid = Drupal::routeMatch()->getRawParameter('node');

Check below the code of this block found in devel module

<?php

namespace Drupal\devel\Plugin\Block;

use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Routing\RedirectDestinationTrait;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\AnonymousUserSession;
use Drupal\Core\Url;
use Drupal\user\Entity\Role;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a block for switching users.
 *
 * @Block(
 *   id = "devel_switch_user",
 *   admin_label = @Translation("Switch user"),
 *   category = "Devel"
 * )
 */
class SwitchUserBlock extends BlockBase implements 
       ContainerFactoryPluginInterface {

  use RedirectDestinationTrait;

  /**
   * The FormBuilder object.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;

  /**
   * The Current User object.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The user storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $userStorage;

  /**
   * Constructs a new SwitchUserBlock object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin 
instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   Current user.
   * @param \Drupal\Core\Entity\EntityStorageInterface $user_storage
   *   The user storage.
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
   *   The form builder service.
   */
  public function __construct(array $configuration, $plugin_id, 
$plugin_definition, AccountInterface $current_user, 
EntityStorageInterface $user_storage, FormBuilderInterface $form_builder) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->formBuilder = $form_builder;
    $this->currentUser = $current_user;
    $this->userStorage = $user_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, 
array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user'),
      $container->get('entity.manager')->getStorage('user'),
      $container->get('form_builder')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'list_size' => 12,
      'include_anon' => FALSE,
      'show_form' => TRUE,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function blockAccess(AccountInterface $account) {
    return AccessResult::allowedIfHasPermission($account, 'switch users');
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $anonymous = new AnonymousUserSession();
    $form['list_size'] = [
      '#type' => 'number',
      '#title' => $this->t('Number of users to display in the list'),
      '#default_value' => $this->configuration['list_size'],
      '#min' => 1,
      '#max' => 50,
    ];
    $form['include_anon'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Include %anonymous', 
['%anonymous' => $anonymous->getDisplayName()]),
      '#default_value' => $this->configuration['include_anon'],
    ];
    $form['show_form'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Allow entering any user name'),
      '#default_value' => $this->configuration['show_form'],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['list_size'] = $form_state->getValue('list_size');
    $this->configuration['include_anon'] = 
$form_state->getValue('include_anon');
    $this->configuration['show_form'] = $form_state->getValue('show_form');
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return 0;
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];
    if ($accounts = $this->getUsers()) {
      $build['devel_links'] = $this->buildUserList($accounts);

      if ($this->configuration['show_form']) {
        $build['devel_form'] = 
$this->formBuilder->getForm('\Drupal\devel\Form\SwitchUserForm');
      }
    }

    return $build;
  }

  /**
   * Provides the list of accounts that can be used for the user switch.
   *
   * Inactive users are omitted from all of the following db selects. Users
   * with 'switch users' permission and anonymous user if include_anon 
property
   * is set to TRUE, are prioritized.
   *
   * @return \Drupal\Core\Session\AccountInterface[]
   *   List of accounts to be used for the switch.
   */
  protected function getUsers() {
    $list_size = $this->configuration['list_size'];
    $include_anonymous = $this->configuration['include_anon'];

    $list_size = $include_anonymous ? $list_size - 1 : $list_size;

    // Users with 'switch users' permission are prioritized so
    // we try to load first users with this permission.
    $query = $this->userStorage->getQuery()
      ->condition('uid', 0, '>')
      ->condition('status', 0, '>')
      ->sort('access', 'DESC')
      ->range(0, $list_size);

    $roles = user_roles(TRUE, 'switch users');

    if (!empty($roles) && !isset($roles[Role::AUTHENTICATED_ID])) {
      $query->condition('roles', array_keys($roles), 'IN');
    }

    $user_ids = $query->execute();

    // If we don't have enough users with 'switch users' permission, add
    // uids until we hit $list_size.
    if (count($user_ids) < $list_size) {
      $query = $this->userStorage->getQuery()
        ->condition('uid', 0, '>')
        ->condition('status', 0, '>')
        ->sort('access', 'DESC')
        ->range(0, $list_size);

      // Excludes the prioritized user ids only if the previous query 
return
      // some records.
      if (!empty($user_ids)) {
        $query->condition('uid', array_keys($user_ids), 'NOT IN');
        $query->range(0, $list_size - count($user_ids));
      }

      $user_ids += $query->execute();
    }

    /** @var \Drupal\Core\Session\AccountInterface[] $accounts */
    $accounts = $this->userStorage->loadMultiple($user_ids);

    if ($include_anonymous) {
      $anonymous = new AnonymousUserSession();
      $accounts[$anonymous->id()] = $anonymous;
    }

    uasort($accounts, 'static::sortUserList');

    return $accounts;
  }

  /**
   * Builds the user listing as renderable array.
   *
   * @param \Drupal\core\Session\AccountInterface[] $accounts
   *   The accounts to be rendered in the list.
   *
   * @return array
   *   A renderable array.
   */
  protected function buildUserList(array $accounts) {
    $links = [];

    foreach ($accounts as $account) {
      $links[$account->id()] = [
        'title' => $account->getDisplayName(),
        'url' => Url::fromRoute('devel.switch', ['name' => 
$account->getAccountName()]),
        'query' => $this->getDestinationArray(),
        'attributes' => [
          'title' => $account->hasPermission('switch users') ? 
$this->t('This user can switch back.') 
: $this->t('Caution: this user will be unable to switch back.'),
        ],
      ];

      if ($account->isAnonymous()) {
        $links[$account->id()]['url'] = Url::fromRoute('user.logout');
      }

      if ($this->currentUser->id() === $account->id()) {
        $links[$account->id()]['title'] = 
ew FormattableMarkup('<strong>%user</strong>', 
['%user' => $account->getDisplayName()]);
      }
    }

    return [
      '#theme' => 'links',
      '#links' => $links,
      '#attached' => ['library' => ['devel/devel']],
    ];
  }

  /**
   * Helper callback for uasort() to sort accounts by last access.
   *
   * @param \Drupal\Core\Session\AccountInterface $a
   *   First account.
   * @param \Drupal\Core\Session\AccountInterface $b
   *   Second account.
   *
   * @return int
   *   Result of comparing the last access times:
   *   - -1 if $a was more recently accessed
   *   -  0 if last access times compare equal
   *   -  1 if $b was more recently accessed
   */
  public static function sortUserList(AccountInterface $a, 
AccountInterface $b) {
    $a_access = (int) $a->getLastAccessedTime();
    $b_access = (int) $b->getLastAccessedTime();

    if ($a_access === $b_access) {
      return 0;
    }

    // User never access to site.
    if ($a_access === 0) {
      return 1;
    }

    return ($a_access > $b_access) ? -1 : 1;
  }

}
Dependency Injection and Route Information in a block, drupal 8.