Search code examples
databasedelphisessionindy

Delphi Indy 10 HTTPServer bind database instance to session


Is there any best practice to bind database connection instances to INDY HTTP Server sessions?

I store usual session data in ARequestInfo.Session.Content.Values but this is only for strings. My current approach for database objects is (TDatabaseis just an example class):

  • Create a TDictionary<String,TDatabase>.
  • Create TDatabase instances for every session and store references along with the session id in the dictionary.
  • Access the dictionary enclosed in critical sections within the session processing to be thread safe.
  • Destroy TDatabase instances when sessions are destroyed.

I suspect that my approach is overhead and there are much more elegant ways to achieve what I want. If this is the case - Tips are very welcome.


Solution

  • The Session.Content property is a TStrings, which can hold strings AND TObject pointers. You don't need a separate TDictionary to map strings to objects, you can store them together in the Content itself.

    Alternatively, you can derive a new class from TIdHTTPSession, add your database connection to that class, and then use the TIdHTTPServer.OnCreateSession event to create instances of that class. Then, to access the database connection, simply typecast any TIdHTTPSession object to your class type.