How can I create a custom service? I've been following instructions on the web on creating a new service, but I can't seem to get it to work.

In my controller:

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyController extends ControllerBase {
  public function myroute() {
      $db = \Drupal::service('mymodule.db');
      return array('DEBUG');
  }
} 


In my mymodule.services.yml:

services:
  mymodule.db:
    class: Drupal\mymodule\mymoduleDB


In my service class:

namespace Drupal\mymodule;

class mymoduleDB {
  public function dosomething() {
    return 'data...';
  }
}


In my controller, when I comment out the line that calls \Drupal::service, then the controller works, so it's an issue with calling the service.

I'm getting a HTTP 500 error.
Create mymodule.services.yml

services:
  mymodule.custom_services:
    class: Drupal\mymodule\Services\CustomService
    arguments: []


Now create Services folder under your mymodule/src. After that create CustomService.php in Service folder.

In CustomService.php 

&lt;?php

namespace Drupal\mymodule\Services;

/**
 * Class CustomService.
 */
class CustomService {

  /**
   * Constructs a new CustomService object.
   */
  public function __construct() {

  }

  public function getServiceData() {
    //Do something here to get any data.
  }
  /**
   * Here you can pass your values as $array.
   */
  public function postServiceData($array) {
    //Do something here to post any data.
  }
}


And for accessing service in your module file

$service = \Drupal::service('mymodule.custom_services');
$service-&gt;getServiceData();