Search code examples
asp.netdatabaseenterprise-library

Is static caching DatabaseFactory.CreateDatabase acceptable?


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


Solution

  • 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.