Search code examples
architectured

How to manage database connections?


Where is a good place to hold a database connection? I'm going to use in a bunch of different places, so it's be nice to be able to access it from somewhere and not have to always pass it around.


Solution

  • All my applications have "ApplicationModel" class/struct where, depending on number of DB connections, I either have a single member variable (in the case I deal only with a single connection), or I have a simple array of DB connnections. Naturally, ApplicationModel has accessor for it.

    I pass around a reference to the ApplicationModel in constructors of those objects that need it. Alternative is to make ApplicationModel a Singleton with the same functionality. - Then you do not need to pass it around... I stopped using Singleton for this purpose not so long ago as I find dependency injection more useful.