In general when you add attachments to a build array, then add the cache metadata in the same place:
$build = [];
// attach libraries and their drupal settings
$build['#attached'] = [...];
// add the cache dependencies for this data
$build['#cache'] = [
'contexts' => ['url'],
'tags' => ['dtm_global'],
'max-age' => 60,
];
If you want to add cacheable dependencies of objects to the build array, you can use addCacheableDependency()
, see https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays
Now sharing this with other modules is no problem anymore, drupalDrupal builds a page with hundreds of different buildrender arrays like this, all from different modules.