How to pass argument in service with dependency injection In a custom module, I have a custom service that uses GuzzleHttp\Client service.

mymodule.services.yml:

services:
  mymodule.mymodule_call:
    class: Drupal\mymodule\MyModuleCall
    arguments: ['@http_client']


The MyModuleCall is using dependency injection and start like:

namespace Drupal\mymodule;

use GuzzleHttp\Client;

class MyModuleCall {

  protected $client;

  public function __construct(Client $client) {
        $this-&gt;client  = $client;
  }

}


As explained in the GuzzleHttp documentation (http://docs.guzzlephp.org/en/latest/quickstart.html), we can pass an argument to the Client constructor to set the base_uri.

Like so: 

use GuzzleHttp\Client;

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' =&gt; 'http://httpbin.org'
]);


How do we set the 'base_uri' in the constructor when we use dependency injection to instantiate a class?
While it would not be possible to use the http_client service it is possible to use the factory service (or create your own factory service if you choose not to rely on core methods).

The http_client_factory service provides a fromOptions method.

The Symfony2 documentation has a section on using parameters:


  Use the parameters section of a config file to set parameters:


parameters:
  mymodule.http_client.config:
    base_uri: 'http://httpbin.org'

services:
  mymodule.http_client:
    factory: '@http_client_factory:fromOptions'
    arguments: ['%mymodule.http_client.config%']
  mymodule.mymodule_call:
    class: Drupal\mymodule\MyModuleCall
    arguments: ['@mymodule.http_client']


Now the MyModuleClass will use Guzzle with Drupal's default configuration and custom configuration.

Note: it is also possible to provide your own factory service for Guzzle and to use that directly. This would be useful if you need to use your own overridden Guzzle\Http\Client class (I do this in a contrib module). This would probably be necessary to inject custom configuration such as handler stack (OAuth1).