Question

If I crate a static DB Connection into a C# Web service

This instance of connection is shared on all istance of web service? So, In this way could I have problem some this?

Not allowed to change the 'ConnectionString' property while the connection (state=Connecting)

I get the instance in this way:

  public static OleDbConnection GetDatabaseConnection(string aConnectionString) 
  {
   if (_dbConnection == null) 
   {
    _dbConnection = new OleDbConnection(aConnectionString);
    _dbConnection.Open();
   }
   else 
   {
    _dbConnection.Close();
    _dbConnection = new OleDbConnection(aConnectionString);
    _dbConnection.Open();
   }
   Log.Logger.log("Aperta connessione al DB");
   return _dbConnection;
  }
Was it helpful?

Solution

It is always a bad practice to keep a global connection instance. You should follow the standard pattern: create, open, use, close and destroy.
Working against this will result, sooner or later, in problems.
The Connection Pooling mechanism has been studied just for this.
The Pool will help you to avoid this bad habit to keep an object so expensive like a database connection open for unforeseeable time

public static OleDbConnection GetDatabaseConnection(string aConnectionString) 
{
    OleDbConnection odb = new OleDbConnection(aConnectionString);
    odb.Open();
    Log.Logger.log("Aperta connessione al DB");
    return odb;
}

then your client code use the using statement to close and destroy the connection

using(OleDbConnection cn = SqlClassHelper.GetDatabaseConnection(constring))
{

    // define here your OleDbCommand, OleDbDataReader etc...
    // use the objects

} // <- here the closing brace close and destroy the connection

OTHER TIPS

Yes, you will have problems with your code in a multithreaded web service.

Your function GetDatabaseConnection works like a factory, everybody who calls it gets a new instance of connection. You do not need static _dbConnection class member, just make it a local variable:

  public static OleDbConnection GetDatabaseConnection(string aConnectionString) 
  {
    OleDbConnection _dbConnection  = new OleDbConnection(aConnectionString);
    _dbConnection.Open();
    Log.Logger.log("Aperta connessione al DB");
    return _dbConnection;
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top