Hi Narf,
From your description, I cannot find how to get the database id. Maybe you send database id from HttpServletRequest, Maybe you configured database id in a properties file. Maybe something else.
So I just can tell you how to get variable from environment. Here is the way to configure a variable in transaction-context and get it from in IdentitySession.
<transaction-context>
<string name="databaseId" value="databaseId"/>
</transaction-context>
EnvironmentImpl.getFromCurrent("databaseId")