Drupal - How to inject the database connection into a custom service?

You can't inject Drupal\Core\Database\Database, it's a container of static functions, constants, & variables for core database functions.

If you'd like to inject the Connection object, that is be possible, and is more like something you want (unless you have scenario where setting.php is dynamic an all possible values of $schema can't be known).

You can follow the example Drupal sets with the default @database class in core.services.yml:

  database:
    class: Drupal\Core\Database\Connection
    factory: Drupal\Core\Database\Database::getConnection
    arguments: [default]

In your mymodule.services.yml you can define the factory/arguments for each database connection you have, plus your DataAccess service class with the injected connections.

services:
  mymodule.database_schema:
    class: Drupal\Core\Database\Connection
    factory: Drupal\Core\Database\Database::getConnection
    arguments: [default, schema]
  mymodule.database_schema2:
    class: Drupal\Core\Database\Connection
    factory: Drupal\Core\Database\Database::getConnection
    arguments: [default, schema2]
  mymodule.data_access:
    class: Drupal\mymodule\DataAccess
    arguments: ['@mymodule.database_schema', '@mymodule.database_schema2']

From there you can store the database connections in DataAccess's constructor and reference them as required by DataAccess's methods.


As commented on another answer, the answer here is probably, you can't.

The database API isn't fully converted to use services. I tried to do it for quite some time, in https://www.drupal.org/node/1811730, but didn't succeed and neither did others.

So, for now, you need to use the static methods. The best you can do is wrap it in a method or another service that does just that to simplify mocking it when you want to write unit tests.