How do I inject a dependency into a @FieldType plugin? I am implementing custom fields in Drupal 8 (types, widgets, formatters).

@FieldType plugins are instantiated by their respective plugin manager (\Drupal\Core\Field\FieldTypePluginManager) which does not care about dependency injection.  That is possible for both @FieldFormatter and @FieldWidget plugins if they only implement \Drupal\Core\Plugin\ContainerFactoryPluginInterface.

What would be the alternative way to inject a dependency into a @FieldType plugin?

Notes


@FieldType plugins are actually (implicitely) instantiated by \Drupal\Core\TypedData\TypedDataManager, which does not care about dependency injection
Related drupal.org issue: Allow typed data plugins to receive injected dependencies
An example for a field formatter plugin with dependency injections. This works differently from services. First parameter injected is the container to get all services needed.

Drupal\Core\Field\Plugin\Field\FieldFormatter

class StringFormatter extends FormatterBase implements ContainerFactoryPluginInterface {

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

  /**
   * Constructs a StringFormatter instance.
   *
   * @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
   *   Any third party settings settings.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
    $this-&gt;entityTypeManager = $entity_type_manager;
  }

  /**
   * {@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-&gt;get('entity_type.manager')
    );
  }