title: Drupal 8 - Add custom cache context
body: <p>I have the following situation: I want to hide or show some local Tasks (Tabs) based on a field on the current user. Therefore I have implemented a <code>hook_menu_local_tasks_alter() in my_module/my_module.module</code>:</p>
  
  <pre><code>function my_module_menu_local_tasks_alter(&amp;$data, $route_name, \Drupal\Core\Cache\RefinableCacheableDependencyInterface &amp;$cacheability) {
    ... some logic ...
  
    if ($user-&gt;get('field_my_field')-&gt;getValue() === 'some value')
      unset($data['tabs'][0]['unwanted_tab_0']);
      unset($data['tabs'][0]['unwanted_tab_1']);
  
    ... some logic ...
  }
  </code></pre>
  
  <p>This works fine but I need to clear the caches if the value of <code>field_my_field</code> changes.</p>
  
  <p>So I found that I need to implement a Cache Context like this in my <code>my_module_menu_local_tasks_alter</code>:</p>
  
  <pre><code>$cacheability
    -&gt;addCacheTags([
      'user.available_regions',
    ]);
  </code></pre>
  
  <p>I have defined my Cache Context like this:</p>
  
  <p><code>my_module/my_module.services.yml</code>:</p>
  
  <pre><code>services:
    cache_context.user.available_regions:
      class: Drupal\my_module\CacheContext\AvailableRegions
      arguments: ['@current_user']
      tags:
        - { name: cache.context }
  
  </code></pre>
  
  <p><code>my_module/src/CacheCotext/AvailableRegions.php:</code></p>
  
  <pre><code>&lt;?php
  
  namespace Drupal\content_sharing\CacheContext;
  
  use Drupal\Core\Cache\CacheableMetadata;
  use Drupal\Core\Cache\Context\CacheContextInterface;
  use Drupal\Core\Session\AccountProxyInterface;
  
  /**
  * Class AvailableRegions.
  */
  class AvailableRegions implements CacheContextInterface {
  
    protected $currentUser;
  
    /**
     * Constructs a new DefaultCacheContext object.
     */
    public function __construct(AccountProxyInterface $current_user) {
      $this-&gt;currentUser = $current_user;
    }
  
    /**
    * {@inheritdoc}
    */
    public static function getLabel() {
      return t('Available sub pages.');
    }
  
    /**
    * {@inheritdoc}
    */
    public function getContext() {
      // Actual logic of context variation will lie here.
      $field_published_sites = $this-&gt;get('field_published_sites')-&gt;getValue();
  
      $sites = [];
      foreach ($field_published_sites as $site) {
        $sites[] = $site['target_id'];
      }
  
      return implode('|', $sites);
    }
  
    /**
    * {@inheritdoc}
    */
    public function getCacheableMetadata() {
      return new CacheableMetadata();
    }
  
  }
  
  </code></pre>
  
  <p>But every time I change the value of my field <code>field_my_field</code> I still need to clear the caches, so the Context is not working. Could anybody point me in the right direction how to get this solved or how to debug such kind of thigs?</p>