diff --git a/realname.services.yml b/realname.services.yml
index cf4fe9b..cf8903f 100644
--- a/realname.services.yml
+++ b/realname.services.yml
@@ -4,8 +4,3 @@ services:
     arguments: ['@cache_tags.invalidator']
     tags:
       - { name: event_subscriber }
-
-  realname.route.subscriber:
-    class: Drupal\realname\Routing\RealnameRouteSubscriber
-    tags:
-      - { name: event_subscriber }
diff --git a/src/Controller/RealnameAutocompleteController.php b/src/Controller/RealnameAutocompleteController.php
deleted file mode 100644
index fd536d5..0000000
--- a/src/Controller/RealnameAutocompleteController.php
+++ /dev/null
@@ -1,107 +0,0 @@
-<?php
-
-namespace Drupal\realname\Controller;
-
-use Drupal\system\Controller\EntityAutocompleteController;
-use Drupal\Component\Utility\Crypt;
-use Drupal\Component\Utility\Tags;
-use Drupal\Component\Utility\Unicode;
-use Drupal\Core\Database\Query\Condition;
-use Drupal\Core\Site\Settings;
-use Drupal\user\Entity\User;
-use Symfony\Component\HttpFoundation\JsonResponse;
-use Symfony\Component\HttpFoundation\Request;
-use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
-
-/**
- * Defines a route controller for entity autocomplete form elements.
- */
-class RealnameAutocompleteController extends EntityAutocompleteController {
-
-  /**
-   * {@inheritdoc}
-   */
-  public function handleAutocomplete(Request $request, $target_type, $selection_handler, $selection_settings_key) {
-    if ($target_type != 'user') {
-      return parent::handleAutocomplete($request, $target_type, $selection_handler, $selection_settings_key);
-    }
-
-    $matches = [];
-    if ($input = $request->query->get('q')) {
-      $typed_string = Tags::explode($input);
-      $typed_string = Unicode::strtolower(array_pop($typed_string));
-      $selection_settings = $this->keyValue->get($selection_settings_key, FALSE);
-      if ($selection_settings !== FALSE) {
-        $selection_settings_hash = Crypt::hmacBase64(serialize($selection_settings) . $target_type . $selection_handler, Settings::getHashSalt());
-        if ($selection_settings_hash !== $selection_settings_key) {
-          throw new AccessDeniedHttpException('Invalid selection settings key.');
-        }
-      }
-      else {
-        throw new AccessDeniedHttpException();
-      }
-
-      $matches = $this->getMatches($selection_settings, $typed_string);
-    }
-
-    return new JsonResponse($matches);
-  }
-
-  /**
-   * Gets matched labels based on a given search string.
-   *
-   * @param array $selection_settings
-   *   An array of settings that will be passed to the selection handler.
-   * @param string $string
-   *   (optional) The label of the entity to query by.
-   *
-   * @return array
-   *   An array of matched entity labels, in the format required by the AJAX
-   *   autocomplete API (e.g. array('value' => $value, 'label' => $label)).
-   *
-   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
-   *   Thrown when the current user doesn't have access to the specified entity.
-   */
-  protected function getMatches($selection_settings, $string = '') {
-    $matches = [];
-
-    if (isset($string)) {
-      // Get an array of matching entities.
-      $match_operator = !empty($selection_settings['match_operator']) ? $selection_settings['match_operator'] : 'CONTAINS';
-      $include_anonymous = isset($selection_settings['include_anonymous']) ? $selection_settings['include_anonymous'] : TRUE;
-
-      $connection = \Drupal::database();
-      $query = $connection->select('users_field_data', 'u');
-      $query->fields('u', ['uid']);
-      $query->leftJoin('realname', 'rn', 'u.uid = rn.uid');
-      if ($match_operator == 'CONTAINS') {
-        $query->condition((new Condition('OR'))
-          ->condition('rn.realname', '%' . $connection->escapeLike($string) . '%', 'LIKE')
-          ->condition('u.name', '%' . $connection->escapeLike($string) . '%', 'LIKE')
-        );
-      }
-      else {
-        $query->condition((new Condition('OR'))
-          ->condition('rn.realname', $connection->escapeLike($string) . '%', 'LIKE')
-          ->condition('u.name', $connection->escapeLike($string) . '%', 'LIKE')
-        );
-      }
-      if ($include_anonymous == FALSE) {
-        $query->condition('u.uid', 0, '>');
-      }
-      $query->range(0, 10);
-      $uids = $query->execute()->fetchCol();
-      $accounts = User::loadMultiple($uids);
-
-      /* @var $account User */
-      foreach ($accounts as $account) {
-        $matches[] = [
-          'value' => t('@realname (@id)', ['@realname' => $account->getDisplayName(), '@id' => $account->id()]),
-          'label' => t('@realname (@username)', ['@realname' => $account->getDisplayName(), '@username' => $account->getAccountName()]),
-        ];
-      }
-    }
-    return $matches;
-  }
-
-}
diff --git a/src/Plugin/EntityReferenceSelection/RealnameSelection.php b/src/Plugin/EntityReferenceSelection/RealnameSelection.php
new file mode 100644
index 0000000..6694bc8
--- /dev/null
+++ b/src/Plugin/EntityReferenceSelection/RealnameSelection.php
@@ -0,0 +1,65 @@
+<?php
+
+namespace Drupal\realname\plugin\EntityReferenceSelection;
+
+use Drupal\Core\Database\Query\Condition;
+use Drupal\user\Plugin\EntityReferenceSelection\UserSelection;
+
+/**
+ * Provides Realname features to user autocomplete plugin.
+ *
+ * @EntityReferenceSelection(
+ *   id = "realname",
+ *   label = @Translation("Realname user selection"),
+ *   entity_types = {"user"},
+ *   group = "realname",
+ *   weight = 1
+ * )
+ */
+class RealnameSelection extends UserSelection {
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
+    // Call the parent method without match string to get the rest of the query.
+    $entity_query = parent::buildEntityQuery(NULL, $match_operator);
+
+    // Load the uids that match the Realname value and add the query condition.
+    if (isset($match)) {
+      $uids = $this->getRealnameMatches($match, $match_operator);
+      if (!empty($uids)) {
+        $entity_query->condition('uid', $uids, 'IN');
+      }
+    }
+
+    return $entity_query;
+  }
+
+  /**
+   * Gets the uids of realname referenceable entities.
+   *
+   * @param string $match
+   *   Text to match the label against.
+   * @param string $match_operator
+   *   The operation the matching should be done with.
+   *
+   * @return array
+   *   The list of uids that match the Realname value.
+   */
+  protected function getRealnameMatches($match, $match_operator) {
+    $query = $this->connection->select('users_field_data', 'u');
+    $query->fields('u', ['uid']);
+    $query->leftJoin('realname', 'rn', 'u.uid = rn.uid');
+    if ($match_operator == 'CONTAINS') {
+      $query->condition((new Condition('OR'))->condition('rn.realname', '%' . $this->connection->escapeLike($match) . '%', 'LIKE')->condition('u.name', '%' . $this->connection->escapeLike($match) . '%', 'LIKE'));
+    }
+    else {
+      $query->condition((new Condition('OR'))->condition('rn.realname', $this->connection->escapeLike($match) . '%', 'LIKE')->condition('u.name', $this->connection->escapeLike($match) . '%', 'LIKE'));
+    }
+
+    $uids = $query->distinct()->execute()->fetchCol();
+    return $uids;
+  }
+
+}
diff --git a/src/Routing/RealnameRouteSubscriber.php b/src/Routing/RealnameRouteSubscriber.php
deleted file mode 100644
index fe927de..0000000
--- a/src/Routing/RealnameRouteSubscriber.php
+++ /dev/null
@@ -1,20 +0,0 @@
-<?php
-
-namespace Drupal\realname\Routing;
-
-use Drupal\Core\Routing\RouteSubscriberBase;
-use Symfony\Component\Routing\RouteCollection;
-
-/**
- * Subscriber for routes.
- */
-class RealnameRouteSubscriber extends RouteSubscriberBase {
-  /**
-   * {@inheritdoc}
-   */
-  protected function alterRoutes(RouteCollection $collection) {
-    if ($route = $collection->get('system.entity_autocomplete')) {
-      $route->setDefault('_controller', '\Drupal\realname\Controller\RealnameAutocompleteController::handleAutocomplete');
-    }
-  }
-}
diff --git a/src/Tests/Kernel/RealnameEntityReferenceTest.php b/src/Tests/Kernel/RealnameEntityReferenceTest.php
new file mode 100644
index 0000000..4794bb5
--- /dev/null
+++ b/src/Tests/Kernel/RealnameEntityReferenceTest.php
@@ -0,0 +1,100 @@
+<?php
+
+namespace Drupal\realname\Tests\Kernel;
+
+use Drupal\field\Entity\FieldConfig;
+use Drupal\Tests\user\Kernel\UserEntityReferenceTest;
+
+/**
+ * Tests the user reference field functionality.
+ *
+ * @group Realname
+ */
+class RealnameEntityReferenceTest extends UserEntityReferenceTest {
+
+  /**
+   * Modules to enable.
+   *
+   * @var array
+   */
+  public static $modules = [
+    'user',
+    'system',
+    'field',
+    'text',
+    'filter',
+    'entity_test',
+    // Add realname module to the list included in parent class.
+    'realname',
+  ];
+
+  /**
+   * {@inheritdoc}
+   */
+  protected function setUp() {
+    parent::setUp();
+    $this->installSchema('realname', 'realname');
+  }
+
+  /**
+   * Tests user selection by roles.
+   */
+  public function testRealnameSelectionByRole() {
+    $pattern = \Drupal::configFactory()->getEditable('realname.settings');
+    $pattern->set('pattern', '[user:mail]')->save();
+
+    $field_definition = FieldConfig::loadByName('user', 'user', 'user_reference');
+    $handler_settings = $field_definition->getSetting('handler_settings');
+    $handler_settings['filter']['role'] = [
+      $this->role1->id() => $this->role1->id(),
+      $this->role2->id() => 0,
+    ];
+    $handler_settings['filter']['type'] = 'role';
+    $field_definition->setSetting('handler_settings', $handler_settings);
+    $field_definition->save();
+
+    $user1 = $this->createUser(['name' => 'aabb', 'mail' => 'arnedo@city.com']);
+    $user1->addRole($this->role1->id());
+    $user1->save();
+
+    $user2 = $this->createUser(['name' => 'aabbb', 'mail' => 'astudillo@city.com']);
+    $user2->addRole($this->role1->id());
+    $user2->save();
+
+    $user3 = $this->createUser(['name' => 'aabbbb', 'mail' => 'valladolid@city.com']);
+    $user3->addRole($this->role2->id());
+    $user3->save();
+
+    /** @var \Drupal\Core\Entity\EntityAutocompleteMatcher $autocomplete */
+    $autocomplete = \Drupal::service('entity.autocomplete_matcher');
+
+    // Test user name autocomplete feature, as in User module.
+    $matches = $autocomplete->getMatches('user', 'realname', $field_definition->getSetting('handler_settings'), 'aabb');
+    $this->assertEquals(count($matches), 2);
+    $users = [];
+    foreach ($matches as $match) {
+      $users[] = $match['label'];
+    }
+    $this->assertTrue(in_array($user1->label(), $users));
+    $this->assertTrue(in_array($user2->label(), $users));
+    $this->assertFalse(in_array($user3->label(), $users));
+
+    $matches = $autocomplete->getMatches('user', 'realname', $field_definition->getSetting('handler_settings'), 'aabbbb');
+    $this->assertEquals(count($matches), 0, '');
+
+    // Test real name autocomplete feature, provided by Realname module.
+    $matches = $autocomplete->getMatches('user', 'realname', $field_definition->getSetting('handler_settings'), 'city');
+    $this->assertEquals(count($matches), 2);
+    $users = [];
+    foreach ($matches as $match) {
+      $users[] = $match['label'];
+    }
+    $this->assertTrue(in_array($user1->label(), $users));
+    $this->assertTrue(in_array($user2->label(), $users));
+    $this->assertFalse(in_array($user3->label(), $users));
+
+    $matches = $autocomplete->getMatches('user', 'realname', $field_definition->getSetting('handler_settings'), 'valla');
+    $this->assertEquals(count($matches), 0, '');
+  }
+
+}
