Assign roles at registration
Oneway you can do is using hook_form_alter()

function MYMODULE_form_user_register_form_alter(&amp;$form, FormStateInterface $form_state, $form_id) {
     foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' &amp;&amp; isset($form['actions'][$action]['#type']) &amp;&amp; $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = '_add_role_submit';
        }
      }
}
/**
 * Implements submit to set role to user.
 */
function _add_role_submit(array &amp;$form, FormStateInterface $form_state) {
  $values = $form_state-&gt;getValues();
// HERE YOU CAN SET ANY ROLE FOR USER.
}


Another way is using hook_user_insert()

use Drupal\user\UserInterface;
function MYMODULE_user_insert(UserInterface $user) {
  // HERE YOU CAN SET ANY ROLE FOR USER.
}