Answering my question and looking forward to review: I just had to implement a new class that implements ConfigFactoryOverrideInterface, following the d.o. documentation on Configuration override system > Providing overrides from modules:
namespace Drupal\custom\Config;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Config\ConfigFactoryOverrideInterface;
class CustomConfigOverriderDisableAds implements ConfigFactoryOverrideInterface {
/**
* {@inheritdoc}
*/
public function loadOverrides($names) {
$overrides = [];
if (in_array('custom_ads.settings', $names)) {
// Disables ads from custom_ads module.
$overrides['custom_ads.settings'] = ['active' => false];
}
return $overrides;
}
/**
* {@inheritdoc}
*/
public function getCacheSuffix() {
return 'CustomConfigOverriderDisableAds';
}
/**
* {@inheritdoc}
*/
public function getCacheableMetadata($name) {
return new CacheableMetadata();
}
/**
* {@inheritdoc}
*/
public function createConfigObject($name, $collection = StorageInterface::DEFAULT_COLLECTION) {
return NULL;
}
}
In my custom controller I just had to conditionally add the override:
namespace Drupal\custom\Controller;
use Drupal\custom\Config\CustomConfigOverriderDisableAds;
use Drupal\Core\Controller\ControllerBase;
class CustomPathController extends ControllerBase {
/**
* Display custom page.
*/
public function content() {
// Add the config override to disable ads for this route.
\Drupal::configFactory()->addOverride(new CustomConfigOverriderDisableAds());
return [
'#type' => 'inline_template',
'#template' => 'Custom content',
];
}
}
Do not add the custom overrider to custom.services.yml, otherwise it will always get called!