views:

310

answers:

1

Is it acceptable to cache an instance of the database connection on application start?

Looking at the MSDN documentation on thread safety, I quote:

Any public static [...] members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Given that, is it acceptable/safe for code such as this example below:

public static class BookingMapper
{
  public static Database Db { get; set; }

  static BookingMapper()
  {
    Db = DatabaseFactory.CreateDatabase();
  }

  public static string GetBooking(int id)
  {
    using (DbCommand cmd = Db.GetStoredProcCommand("getBooking"))
    {
      Db.AddInParameter(cmd, "@Id", DbType.Int32, id);
      using (IDataReader dr = Db.ExecuteReader(cmd))
      {
        ...
      }
    }
  }
}

If it is acceptable, what are the benefits/drawbacks of using such an approach over simply instantiating the Database on every single method call?

Thanks in advance.

Update:

Further research has pointed me to a PrimaryObjects.com article which, in the Putting the Database Factory to Use section suggests that this is acceptable. But I'm still wondering if there are pros/cons to doing it this way?

Similar question

+2  A: 

1) There are two ways to interpret that standard phrase on Thread Safety from MSDN, and I wish they'd clarify it. Your interpretation would be nice, but I believe that what it means is that:

Any members (methods, fields, properties, etc) that are part of this type, and that are public and static, are thread safe

(e.g. there are two ways to interpret the subphrase "members of this type")

2) Generally, you don't want to share a db connection around - you want to open a connection, do your job, and close it. You can't generally have multiple open readers associated with a single connection (this is generic db/connection advice, not ent library specific).

3) On some further reading inside the ent library, the Database object returned by the CreateDatabase call isn't a connection itself, and it looks like the connection management is handled as I stated in point 2. So it looks like the Database object itself can be safely shared around.

Damien_The_Unbeliever
@damien, I've done some more searching on this subject and I've been led to http://www.primaryobjects.com/CMS/Article81.aspx as mentioned in my edit. It seems to be okay to do it this way, but there doesn't appear to be any analysis on the pros and cons.
Dan Atkinson
Judging by point 3, there isn't a great deal of benefit past the saving in creating an instance itself.
Dan Atkinson
I made point 3 after looking through the source, which is installable from the "src" directory after installing the ent lib. You can then go in and see how much work is done inside various functions. (Or if you don't want to install the source, Reflector can give you similar information)
Damien_The_Unbeliever