In C# Global Connection To Be Used In All Classes
Solution 1:
You actually don't need to use a single SqlConnection everywhere. A better approach would be to create a class to manage you data access. Typically this is the duty of your Data Access Layer (DAL). DAL is a set of classes that handle all the database related stuff.
A very simple class for this purpose could be something like this:
publicclassDatabaseManager
{
privatestatic DatabaseManager _instance;
privateDatabaseManager()
{
}
staticDatabaseManager()
{
_instance = new DatabaseManager();
}
public DatabaseManager Instance
{
get { return _instance; }
}
privatestringGetConnectionString()
{
return Properties.Settings.Default.MyConnectionString;
}
public SqlConnection CreateConnection()
{
returnnew SqlConnection(GetConnectionString());
}
}
You can extend this class to contain another methods to execute your queries.
I highly recommend you to use an ORM (Object-Relational Mapper) like Entity Framework.
Solution 2:
It can be done with the help of STATIC variable in any class
Solution 3:
Whenever you instantiate a new object pass to its constructor a reference to that connection.
Solution 4:
I've have something similar set up in an old project like so.
It's worth noting that you should always be using a new SqlConnection for all your operations, because of connection pooling.
public staticclassSqlConnectionUtil
{
public staticstring DefaultConnectionString { get; private set; }
staticSqlConnectionUtil()
{
SqlConnectionUril.DefaultConnectionString =
Properties.Settings.Default.TheConnectionString;
}
public static SqlConnection Create()
{
return new SqlConnection(SqlConnectionUtil.DefaultConnectionString);
}
}
You would then use it like this.
using (var connection = SqlConnectionUtil.Create())
{
using (var command = connection.CreateCommand())
{
// do things.
}
}
Post a Comment for "In C# Global Connection To Be Used In All Classes"