How can trusted host patterns be set dynamically?
By design you can't access the database from a non trusted host within Drupal. The kernel checks the trusted host patterns when the settings are read from file, but without the settings you don't have the credentials to open the database connection. 

There are a lot of ways to work around this. As mentioned in the comment by @NoSssweat you can write the trusted hosts to a file and include the file in settings.php. Or you can access the database from outside of Drupal and invoke this PHP script in settings.php. Or use a wildcard trusted host pattern matching all possible domains and then enhance security by adding a second check against the custom domain names in a kernel event subscriber when the database is available.