in c# global connection to be used in all classes

本小妞迷上赌 提交于 2019-12-02 05:43:15

问题


I've a connection string saved to Properties.Settings.Default, i need to use an sql connection in all classes without having to declare it everytime, so how should it be declared?


回答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:

public class DatabaseManager
{
    private static DatabaseManager _instance;
    private DatabaseManager()
    {
    }

    static DatabaseManager()
    {
        _instance = new DatabaseManager();
    }

    public DatabaseManager Instance
    {
        get { return _instance; }
    }

    private string GetConnectionString()
    {
        return Properties.Settings.Default.MyConnectionString;
    }

    public SqlConnection CreateConnection()
    {
        return new 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.




回答2:


It can be done with the help of STATIC variable in any class




回答3:


Whenever you instantiate a new object pass to its constructor a reference to that connection.




回答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 static class SqlConnectionUtil
{
    public static string DefaultConnectionString { get; private set; }

    static SqlConnectionUtil()
    {
        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.
    }
}



回答5:


You can use this code for get coonection string

      var      defaultConn= new SqlConnection(ConfigurationManager.AppSettings["defaultConn"].ToString());


来源:https://stackoverflow.com/questions/15174601/in-c-sharp-global-connection-to-be-used-in-all-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!