Providing RemoteDB-connection based on client


In our company each customer has its own database located on a separate server. The situation is similar to the one at . The connection parameters for each customer database can be retrieved from the customer record in the master database on yet another server. 
I've been trying to create a RemoteDB-module for each client when the server starts. First the server executes a query on the master database to get all customer database credentials. While looping through the query result, it creates a RemoteDB-module for each record like this:

      // serv, portNum, user, pass and datab are the field values for each record in the query result

      //  Assemble remoteDB connection URL based on dossier database name
      remoteDBfullUri := TSparkleUtils.CombineUrlFast(
        datab );
      //  Create connection factory
      clientConnectionFactory := TDBConnectionFactory.Create(
        function: IDBConnection
            Result := CreateStorageDBConnectionInterface(
              datab );
      //  Create module
      remoteDbConnectionModule := TRemoteDBModule.Create(
        clientConnectionFactory );

      //  Set module access credentials
      remoteDbConnectionModule.UserName := user;
      remoteDbConnectionModule.Password := pass;
      remoteDbConnectionModule.DefaultInstanceTimeout := 1000;

      //  Register module on server
      httpServer.AddModule( remoteDbConnectionModule );

Problem is: Currently each RemoteDB module can only create a connection to the client database asociated with the last customer record in the query result.
I think this because the anonymous function stored in each TDBConnectionFactory doesn't capture the parameter values for CreateStorageDBConnectionInterface, only the identifiers.

Is it still possible to use RemoteDB in my case? 

Is that code inside a loop? It  might just a matter of how Delphi handles anonymous functions inside a loop - it will use only the last value of the variable controlling the loop indeed. If that's the case, I'd just suggest you wrap your code at an extra level, moving all the code that creates the connection factory to a function. In other words, create a function like this:

clientConnectionFactory := CreateConnectionFactory(<params>);

and then pass the proper variable params to the function. This will cause the values to be "saved" for each different anonymous functions instead of using just the last one.

The code is inside inside a loop and
wrapping the code at an extra level solved my problem.

Thank you for your quick support!