Hi @Stuart Clennett,
I am happy you found a way to solve by yourself while I was in vacation 🙂
Your solution works but has a couple of things to consider:
1) that BeforeHandleRequest code gets executed for each incoming request (performance)
2) manipulating Parameters is not suggested as App.Parameters is like a global object (IIRC).
You have an other opportunity through (yet another) undocumented MARS feature:
[Context, Connection('Dynamic_MyConnection', True)] FD: TMARSFireDAC;
The Connection attribute specifies the name of the connection definition to be used with the TMARSFireDAC instance injected.
The name supports macros (the second argument enables macro expansion).
You can rely on built-in macros (i.e. using some part of the token, params, username or similar things. A list is available here: https://github.com/andrea-magni/MARS/blob/a8d323558bd591589ef667eac326324302d167a9/Source/MARS.Data.FireDAC.pas#L528 ). Last chance of the macro-expander is looking for custom providers.
You can register your own in the initialization of one of your units or in the Server.Ignition.pas file:
TMARSFireDAC.AddContextValueProvider(
procedure (const AActivation: IMARSActivation;
const AName: string; const ADesiredType: TFieldType; out AValue: TValue)
begin
if SameText(AName, 'Dynamic_MyConnection') then
begin
if Odd(SecondOf(Now))then
AValue := 'OddConnection_' + AActivation.Request.HostName
else
AValue := 'EvenConnection_' + AActivation.Request.HostName;
end;
end
);
Beware: the connection name has to be this format: [PREFIX]_[SUFFIX](_[OTHER_SUFFIX])
Using 'MyConnection' won't work for instance...
Pros of this approach:
1) code is executed only when needed (when the TMARSFireDAC instance gets created to be injected in your resources), all others REST endpoints won't be affected.
2) it seems more isolated to me (but this can be a personal evaluation).
If you need to fix some TFDConnection instances on your datamodules, try having a TMARSFireDAC instance injected in the datamodule itself and use the FD.ConnectionDefName (already expanded once injected) to fix the ConnectionDefName of your components (OnCreate event of the datamodule should be fine, or AfterConstruction method as well).
If you encounter troubles doing this, write here again: there's another hidden feature for you to fix this (when registering the datamodule as resource you can specify an anonymous method to initialize it or to call a custom constructor instead of TDatamodule.Create(AOwner)).
Sincerely,
Andrea