How can I inject a different service in an existing one, i.e. exchange one already injected service by an own one? The basic authentication provider service uses the user.auth service:

basic_auth.authentication.basic_auth:
    class: Drupal\basic_auth\Authentication\Provider\BasicAuth
    arguments: ['@config.factory', '@user.auth', '@flood', '@entity.manager']
    tags:
      - { name: authentication_provider, provider_id: 'basic_auth', priority: 100 }


I wrote an own service my-user.auth (extending UserAuthInterface) and want my service to be injected into the basic authentication provider instead of the user.auth. How can I do this?
Create a ServiceProvider in your module. And then replace the argument using Definition::replaceArguments like so:

&lt;?php

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

// @note: You only need Reference, if you want to change service arguments.
use Symfony\Component\DependencyInjection\Reference;

/**
 * Modifies the language manager service.
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container-&gt;getDefinition('basic_auth.authentication.basic_auth');
    $definition-&gt;replaceArgument(1, 'NEW_SERVICE');
  }
}


Please note:


  Note that if you want this service alteration to be recognized
  automatically, the name of this class is required to be a CamelCase
  version of your module's machine name followed by ServiceProvider, it
  is required to be in your module's top-level namespace
  Drupal\your_module_name, and it must implement
  \Drupal\Core\DependencyInjection\ServiceModifierInterface (which
  ServiceProviderBase does).


Relevant article: https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services